繁体   English   中英

MongoDB + C#驱动程序+查询元素数组,其中每个数组元素包含要查询的子文档

[英]MongoDB + C# driver + query array of elements where each array element contains sub-document to query on

我正在使用官方MongoDB C#驱动程序的1.5.0.4566版。 我正在使用Mongo 2.06版。

这是我的文档结构的样子(省略了本讨论不需要的字段):

{ "Parents" : 
   [ 
     {
     "CreatedOn": ISODate("2012-07-28T15:30:06.623Z"),
     "Title": "Simple Title",
     "Children": [   
                  { "StatusId": 1, "Active" : true, SubChild : { "ExpiresOn": ISODate("2012-07-28T15:30:06.623Z")}},
                  { "StatusId": 1, "Active" : true, SubChild : { "ExpiresOn": ISODate("2012-08-28T15:30:06.623Z")}}
                 ]
     },
     {
     "CreatedOn": ISODate("2012-07-28T15:30:06.623Z"),
     "Title": "Another Simple Title",
     "Children": [   
                  { "StatusId": 1, "Active" : true, SubChild : { "ExpiresOn": ISODate("2012-07-28T15:30:06.623Z")}},
                  { "StatusId": 1, "Active" : true, SubChild : { "ExpiresOn": ISODate("2012-08-28T15:30:06.623Z")}}
                 ]
     }
   ]
}

如果我想查询StatusId等于1并且Active为true的Children,我可以使用ElemMatch。

Query.ElemMatch("Children", Query.And(Query.EQ("StatusId", 1),Query.EQ("Active",true)));

我无法工作的是当我需要在查询中包含SubChild元素时。

Query.ElemMatch("Children", Query.And(Query.EQ("StatusId",1), Query.EQ("Active",true),Query.LT("SubChild.ExpiresOn",DateTime.UtcNow)));

当我尝试在查询中包含SubChild.ExpiresOn字段时,查询不返回任何值。 我已经尝试了不同的方法来构建此查询,但是当我包含SubChild.ExpiredOn字段时,仍然保持零文档。

我错过了什么?

谢谢,

试试这个

Query.ElemMatch("Children", Query.And(Query.EQ("StatusId",1), Query.EQ("Active",true),Query.LT("SubChild.ExpiresOn",DateTime.UtcNow)));

想知道为什么这个查询神奇地起作用? 情况就是这样( StatusId vs StatusID )。 JavaScript区分大小写。

您可以通过使用强类型Linq查询来消除此问题,例如:

from x in collection.AsQueryable()
where x.Children.Any(child => 
    child.StatusId == 1 
    && child.Active 
    && child.SubChild.ExpiresOn < DateTime.UtcNow)
select x

暂无
暂无

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

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