Misi
Misi

Reputation: 748

Complex query filtering of object arrays in MongoDb (C# Driver)

Let's say I have this document.

"Id" : "lot1",
"Fruits" : [
       [{ "Id": "fruit1", "Name": "apple"}, { "Id": "fruit2", "Name": "carrot"}]
       [{ "Id": "fruit3", "Name": "banana"}]
     ]

Q: How can I query the Fruits array by a list of fruits names ?

I have tried like this:

var fruitNames = new List<string>(){ "apple", "banana" };
var builder = Builders<Lot>.Filter;
var filter = builder.AnyIn(l => l.Fruits.Select(f => f.Name), fruitNames); //TAKE 1
var filter = builder.Where(l => l.Fruits.Select(f => f.Name).Any(f => fruitNames.Contains(f)));//TAKE 2
var filter = builder.AnyIn("Fruits.Name", fruitNames );//TAKE 3
var results = mongoContext.Lots.Find(filter).ToList();

I have tried this in 3 different ways with no success.

Upvotes: 0

Views: 2848

Answers (1)

BOR4
BOR4

Reputation: 630

Can you try this? It is a little hack but i am pretty sure it will work:

var filter= Builders<Lot>.Filter.ElemMatch(y => y.fruits, x => fruitNames.Contains(x.name));

Upvotes: 2

Related Questions