简体   繁体   中英

Mongo DB c# query ALL element's property in nested array

I'm trying to get a filter with a certain condition to get documents that have an inner array of documents that have a property:

public class MyObject {
    public List<InnerObject> InnerObjects {get;set;}
}

public class InnerObject {
    public bool Accepted {get;set;}
}

Now I want to query for all MyObjects that have ALL inner objects with Accepted set to a certain value, in this case to FALSE . I built the filter:

filter = Builders<MyObject>.Filter.ElemMatch(
                                c => c.InnerObjects,
                                Builders<InnerObject>.Filter.Eq(c => c.Accepted, false));

Which does not work because as it will also return MyObjects with any instance of InnerObject set to true as well, which I could understand. The thing is I don't find any operator that does what I want to achieve. Note that I wanted to also have a filter with at least an InnerObject with Accept to certain value (in fact the filter from above would achieve that), so my only problem is to get the object will ALL instances of InnerObject.Accepted set to either TRUE or FALSE .

How can this be achieved?

You'll need to do the reverse of it to achieve. Please translate the query into C# syntax.

db.collection.find({
  "InnerObject.Accepted": {
    $not: {
      $eq: true
    }
  }
})

Playground: https://mongoplayground.net/p/SgEpt96uxdb

Following C# syntax (please follow best practices and good OO principles)

        var notAccepted = Builders<InnerObject>.Filter.Not(
            Builders<InnerObject>.Filter.Eq(u => u.Accepted, false)
        );
        
        IMongoCollection<MyObject> myobjectsCollection = null;
        myobjectsCollection.Find(Builders<MyObject>.Filter.ElemMatch(x => x.InnerObjects, notAccepted));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM