using MongoDB.Driver;
using MongoDB.Driver.Linq;
var query = (from a in collectionA.AsQueryable()
join b in collectionB on a.Id equals b.whateverId
where a.AttributeId == 10
select a);
var list = await query.ToListAsync();
Note:
- MongoDB can not filter on joined collectionB
- MongoDB can not use multiple attributes to join collections
- MongoDB can only filter on collectionA with where clause
var query = (from a in collectionA.AsQueryable()
join b in collectionB on a.Id equals b.whateverId
where a.AttributeId == 10
select new ObjectClass
{
Attribute1 = a.Attribute1
Attribute2 = b.Attribute2
});
var list = await query.ToListAsync();
Note:
- you have to define class ObjectClass
- list will be of type list
var filter = collectionA.Find(o => o.Id == "x").Filter;
try
{
var o = await collectionA.Find(filter).Limit(1).Single<CollectionAClass>();
}
catch
{
// not found
}
await collectionA.DeleteManyAsync(filter);
var update = Builders<CollectionAClass>.Update
.Set(o => o.Attribute1, Value1)
.Set(o => o.Attribute2, Value2);
// one
await collectionA.UpdateOneAsync(filter, update);
// or many
await collectionA.UpdateManyAsync(filter, update);
var update = Builders<CollectionAClass>.Update.Inc(o => o.Attribute1, 1);
await collectionA.UpdateOneAsync(filter, update);
var update = Builders<CollectionAClass>.Update.PullFilter(
o => o.Array,
e => e == "STRINGTOPULL");
await collectionA.UpdateOneAsync(filter, update);
var update = Builders<CollectionAClass>.Update
.Set(o => o.Attribute1, Value1)
.Set(o => o.Attribute2, Value2);
await collectionA.UpdateOneAsync(filter, update, new UpdateOptions { IsUpsert = true });
using (IAsyncCursor<CollectionAClass> cursorA = await collectionA.Find(filter).ToCursorAsync())
{
while (await cursorA.MoveNextAsync())
{
foreach (var objA in cursorA.Current)
{
}
}
}
BsonArray subsetBson = new BsonArray();
subsetBson.Add("A");
subsetBson.Add("B");
BsonArray relationOfSetsBson = new BsonArray();
relationOfSetsBson.Add(BsonElement{subSet, "$set"});
var pipelineAggregate = PipelineDefinition<Consumer, BsonDocument>.Create(
new BsonDocument { { "$match", new BsonDocument { { "_id", Id } } } },
new BsonDocument { { "$project", new BsonDocument { { "tags", 1 }, { "IsSubset", new BsonDocument { { "$setIsSubset", subsetBson } } } } } },
new BsonDocument { { "$match", new BsonDocument { { "IsSubset", true } } } });
var aggregate = consumerCollection.Aggregate(pipelineAggregate);
var results = await aggregate.ToListAsync();
Note:
- My ObjectA in the CollectionA has an array of strings called "set"
- the current content of "set" is ["A", "B", "C"]
using (var session = await mongoClient.StartSessionAsync())
{
session.StartTransaction();
try
{
...
await session.CommitTransactionAsync();
}
catch
{
await session.AbortTransactionAsync();
}
}
Note:
- Transactions are only supported on replication sets
- For development you can create a replication set consisting of one node