Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb c# driver find item in array by field value

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 ?

like image 879
Vladyslav Furdak Avatar asked Aug 03 '15 11:08

Vladyslav Furdak


People also ask

Can you use MongoDB with C#?

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.

What is a MongoDB driver?

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.

Is MongoDB paid?

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.


2 Answers

There is ElemMatch

var filter = Builders<Post>.Filter.ElemMatch(x => x.Tags, x => x.Name == "test"); var res = await collection.Find(filter).ToListAsync() 
like image 102
rnofenko Avatar answered Sep 20 '22 09:09

rnofenko


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); } 
like image 39
JBond Avatar answered Sep 23 '22 09:09

JBond