使用嵌套对象表示法查询 mongoDB 时遇到问题:
db.messages.find( { headers : { From: "reservations@marriott.com" } } ).count()
0
db.messages.find( { 'headers.From': "reservations@marriott.com" } ).count()
5
我看不出我做错了什么。我期望嵌套对象表示法返回与点表示法查询相同的结果。我哪里错了?
db.messages.find( { headers : { From: "reservations@marriott.com" } } )
这会查询headers
等于 { From: ... }
的文档,即不包含其他字段。
db.messages.find( { 'headers.From': "reservations@marriott.com" } )
这仅查看 headers.From
字段,不受 headers
中包含或缺少的其他字段的影响。
由于查询 MongoDB 集合与子文档有很多混淆,我认为值得用示例来解释上述答案:
首先,我在集合中只插入了两个对象,即:message
:
> db.messages.find().pretty()
{
"_id" : ObjectId("5cce8e417d2e7b3fe9c93c32"),
"headers" : {
"From" : "reservations@marriott.com"
}
}
{
"_id" : ObjectId("5cce8eb97d2e7b3fe9c93c33"),
"headers" : {
"From" : "reservations@marriott.com",
"To" : "kprasad.iitd@gmail.com"
}
}
>
那么查询的结果是什么: db.messages.find({headers: {From: "reservations@marriott.com"} }).count()
它应该是一个,因为这些对文档的查询headers
等于对象{From: "reservations@marriott.com"}
,仅即不包含其他字段,或者我们应该将整个子文档指定为字段的值。
所以根据@Edmondo1984的回答
如果子文档与指定的子文档(包括字段顺序)完全匹配,则子文档内的相等匹配选择文档。
从上面的语句,下面的查询结果应该是什么?
> db.messages.find({headers: {To: "kprasad.iitd@gmail.com", From: "reservations@marriott.com"} }).count()
0
如果我们改变 From
和 To
的顺序,即与第二个文档的子文档相同,该怎么办?
> db.messages.find({headers: {From: "reservations@marriott.com", To: "kprasad.iitd@gmail.com"} }).count()
1
因此,它与指定的子文档完全匹配,包括字段顺序。
对于使用点运算符,我认为每个人都非常清楚。让我们看看以下查询的结果:
> db.messages.find( { 'headers.From': "reservations@marriott.com" } ).count()
2
我希望以上示例的这些解释将使人们更清楚地了解子文档的查找查询。
正如 子文档 部分的 the docs 中所建议的,这两种查询机制以不同的方式工作:
当字段包含嵌入文档(即子文档)时,您可以将整个子文档指定为字段的值,或者使用点表示法“进入”子文档,以指定子文档中各个字段的值:
如果子文档与指定的子文档(包括字段顺序)完全匹配,则子文档内的相等匹配选择文档。
在以下示例中,查询匹配字段 producer 的值为子文档的所有文档,该子文档仅包含值为 'ABC123'
的字段 company
和值为 '123 Street'
的字段 address
,确切地说命令:
db.inventory.find( {
producer: {
company: 'ABC123',
address: '123 Street'
}
});
conditions['some.path'] = 'value'
之类的操作,然后在最后运行一个查询:find(conditions, fields, callback);
domains.domain.com
。这种情况是否有任何解决方法(不将 domain.com 更改为其他内容,例如 domain_com)?