Edm*_*984 191 syntax nested mongodb bson mongodb-query
使用嵌套对象表示法查询mongoDB时遇到问题:
db.messages.find( { headers : { From: "reservations@marriott.com" } } ).count()
0
db.messages.find( { 'headers.From': "reservations@marriott.com" } ).count()
5
Run Code Online (Sandbox Code Playgroud)
我看不出我做错了什么.我期望嵌套对象表示法返回与点表示法查询相同的结果.我哪里错了?
shx*_*hx2 378
db.messages.find( { headers : { From: "reservations@marriott.com" } } )
这查询headers 等于的 文档{ From: ... },即不包含其他字段.
db.messages.find( { 'headers.From': "reservations@marriott.com" } )
这仅查看该headers.From字段,不受其中包含或缺失的其他字段的影响headers.
Edm*_*984 19
这两个查询机制以不同的方式工作,如Subdocuments部分的文档中所建议的:
当该字段包含嵌入的文档(即子文档)时,您可以将整个子文档指定为字段的值,或使用点表示法"到达" 子文档,以指定子文档中各个字段的值:
如果子文档完全匹配指定的子文档(包括字段顺序),则子文档内的等式匹配选择文档.
在下面的示例中,查询匹配所有文档,其中字段生成器的值是一个子文档,该子文档仅包含company具有值'ABC123'的字段address和具有值的字段,'123 Street'具体顺序如下:
db.inventory.find( {
producer: {
company: 'ABC123',
address: '123 Street'
}
});
Run Code Online (Sandbox Code Playgroud)
kri*_*sad 14
由于查询 MongoDB collection with sub-documents存在很多混淆,我认为值得用示例解释上述答案:
首先,我在集合中只插入了两个对象,即: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"
}
}
>
Run Code Online (Sandbox Code Playgroud)
那么查询的结果是什么:
db.messages.find({headers: {From: "reservations@marriott.com"} }).count()
它应该是一个,因为这些对headers等于 object 的文档的查询{From: "reservations@marriott.com"},仅 ie 不包含其他字段,或者我们应该将整个子文档指定为字段的值。
所以根据@Edmondo1984的回答
如果子文档与指定的子文档完全匹配,包括字段 order ,则子文档中的相等匹配选择文档。
从上面的语句,下面的查询结果应该是什么?
> db.messages.find({headers: {To: "kprasad.iitd@gmail.com", From: "reservations@marriott.com"} }).count()
0
Run Code Online (Sandbox Code Playgroud)
如果我们改变第二个文档的子文档的顺序From和顺序To怎么办?
> db.messages.find({headers: {From: "reservations@marriott.com", To: "kprasad.iitd@gmail.com"} }).count()
1
Run Code Online (Sandbox Code Playgroud)
因此,它与指定的子文档完全匹配,包括字段 order。
对于使用点运算符,我认为每个人都非常清楚。让我们看看以下查询的结果:
> db.messages.find( { 'headers.From': "reservations@marriott.com" } ).count()
2
Run Code Online (Sandbox Code Playgroud)
我希望以上示例的这些解释将使人们更清楚地了解带有子文档的查找查询。
| 归档时间: |
|
| 查看次数: |
152475 次 |
| 最近记录: |