简体   繁体   English

Mongo DB c# 查询嵌套数组中所有元素的属性

[英]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 .现在我想查询所有内部对象的所有MyObjects ,其中Accepted设置为某个值,在本例中为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.这不起作用,因为它还将返回 MyObjects 并将任何 InnerObject 实例也设置为 true,我可以理解。 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 .请注意,我还希望有一个过滤器,其中至少有一个 InnerObject ,其 Accept 为某个值(实际上上面的过滤器可以实现),所以我唯一的问题是让 object 将所有InnerObject.Accepted实例设置为

How can this be achieved?如何做到这一点?

You'll need to do the reverse of it to achieve.你需要做相反的事情来实现。 Please translate the query into C# syntax.请将查询翻译成 C# 语法。

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

Playground: https://mongoplayground.net/p/SgEpt96uxdb游乐场: https://mongoplayground.net/p/SgEpt96uxdb

Following C# syntax (please follow best practices and good OO principles)遵循 C# 语法(请遵循最佳实践和良好的 OO 原则)

        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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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