Kar
Kar

Reputation: 321

Filter in MongoDB

I have this model:

 public class DraftItem
 {
    public List<DraftNode> Nodes{ get; set; }
 }
 public class DraftNodes
 {
     ...
     public List<DraftTerm> Properties{ get; set; }
 }
 public class DraftTerm
 {
    public ObjectId Id{ get; set; }
    public String Name { get; set; }
 }

I need to filter in mongoDB the Properties based on the DraftTerm - Id I've tried like this to make the filter, but it is not working:

 FilterDefinition<DraftNodes> filter = Builders<DraftNodes>.Filter.ElemMatch(z => z.Properties, a => a.Id == id);

 await db.GetCollection<DraftItem>("collection name")
              .Find(filter )
              .ForEachAsync(async document =>
              {..}

In mongoDB it's working if I filter like this:

db.getCollection('collection name').find({'nodes.properties.id': ObjectId('...')})

Is there a way to filter with ElemMatch and Filter?

Upvotes: 1

Views: 283

Answers (1)

mickl
mickl

Reputation: 49945

The easiest way to build this query in a strongly typed way is to run AsQueryable() on your collection and then use LINQ syntax like below:

var query = Col.AsQueryable().Where(
            x => x.Nodes.Any(n => n.Properties.Any(q => q.Id == objectId)));

var result = query.ToList();

Once you run this you can check in MongoDB profiler that it will get translated to Aggregation Framework's $match stage, exactly like your query:

"pipeline" : [
    {
        "$match" : {
            "Nodes.Properties._id" : ObjectId("...")
        }
    }
]

Upvotes: 1

Related Questions