Reputation: 5736
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?
Upvotes: 0
Views: 884
Reputation: 3444
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));
Upvotes: 1