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版.
I'm using version 1.5.0.4566 of the official MongoDB C# driver. I'm using Mongo version 2.06.
这是我的文档结构的样子(此讨论中不需要省略字段):
Here is what my document structure looks like (omitted fields not necessary for this discussion):
{ "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.
If I wanted to query the Children that have a StatusId equal to one and Active is true I can use ElemMatch.
Query.ElemMatch("Children", Query.And(Query.EQ("StatusId", 1),Query.EQ("Active",true)));
当需要在查询中包括SubChild元素时,我无法工作.
What I cannot get to work is when I need to include the SubChild element in my query.
Query.ElemMatch("Children", Query.And(Query.EQ("StatusId",1), Query.EQ("Active",true),Query.LT("SubChild.ExpiresOn",DateTime.UtcNow)));
当我尝试在查询中包括SubChild.ExpiresOn字段时,查询不返回任何值.我尝试了不同的方式来构建此查询,但是当我包含SubChild.ExpiredOn字段时,始终获得零文档.
The query doesn't return any values when I try to include the SubChild.ExpiresOn field in the query. I have tried different ways to build this query, but keep getting zero documents when I include the SubChild.ExpiredOn field.
我想念什么?
谢谢
推荐答案
尝试尝试
Query.ElemMatch("Children", Query.And(Query.EQ("StatusId",1), Query.EQ("Active",true),Query.LT("SubChild.ExpiresOn",DateTime.UtcNow)));
奇怪为什么这个查询神奇地起作用了?就是这种情况(StatusId
与StatusID
). JavaScript区分大小写.
Wondering why this query magically works? It's the case (StatusId
vs StatusID
). JavaScript is case sensitive.
您可以通过使用强类型的Linq查询来消除此问题,例如:
You could eliminate this problem by using strongly typed Linq queries, like:
from x in collection.AsQueryable()
where x.Children.Any(child =>
child.StatusId == 1
&& child.Active
&& child.SubChild.ExpiresOn < DateTime.UtcNow)
select x
这篇关于MongoDB + C#驱动程序+元素查询数组,其中每个数组元素包含要查询的子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!