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

我正在使用官方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