i found the way to check is the value contains in simple array :
var filter = Builders<Post>.Filter.AnyEq(x => x.Tags, "mongodb");
But how to find a complex item with many fields by a concrete field ? I found the way to write it via the dot notation approach with BsonDocument
builder, but how can i do it with typed lambda notations ?
upd
i think it some kind of
builderInst.AnyIn(p => p.ComplexCollection.Select(ml => ml.Id), mlIds)
but can't check right now, is anyone could help ?
By developing with C# and MongoDB together one opens up a world of possibilities. Console, window, and web applications are all possible. As are cross-platform mobile applications using the Xamarin framework.
The official MongoDB Node. js driver allows Node. js applications to connect to MongoDB and work with data. The driver features an asynchronous API which allows you to interact with MongoDB using Promises or via traditional callbacks.
MongoDB allows teams to choose their cloud provider of choice while providing database management that streamlines every aspect of database administration. It's easy to get started with MongoDB Atlas, and it's free.
There is ElemMatch
var filter = Builders<Post>.Filter.ElemMatch(x => x.Tags, x => x.Name == "test"); var res = await collection.Find(filter).ToListAsync()
Here's an example that returns a single complex item from an array (using MongoDB.Driver v2.5.0):
Simple Data Model
public class Zoo { public List<Animal> Animals { get; set; } } public class Animal { public string Name { get; set; } }
Option 1 (Aggregation)
public Animal FindAnimalInZoo(string animalName) { var zooWithAnimalFilter = Builders<Zoo>.Filter .ElemMatch(z => z.Animals, a => a.Name == animalName); return _db.GetCollection<Zoo>("zoos").Aggregate() .Match(zooWithAnimalFilter) .Project<Animal>( Builders<Zoo>.Projection.Expression<Animal>(z => z.Animals.FirstOrDefault(a => a.Name == animalName))) .FirstOrDefault(); // or .ToList() to return multiple }
Option 2 (Filter & Linq) This was about 5x slower for me
public Animal FindAnimalInZoo(string animalName) { // Same as above var zooWithAnimalFilter = Builders<Zoo>.Filter .ElemMatch(z => z.Animals, a => a.Name == animalName); var zooWithAnimal = _db.GetCollection<Zoo>("zoos") .Find(zooWithAnimalFilter) .FirstOrDefault(); return zooWithAnimal.Animals.FirstOrDefault(a => a.Name == animalName); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With