有文档如下:
/* 0 */
{
"_id" : ObjectId("55d09915331c571b60035d95"),
"title" : "hello world",
"comment" : [{
"author" : "joe",
"score" : 3
}, {
"author" : "tom",
"score" : 5
}, {
"author" : "jean",
"score" : 9
}]
}
/* 1 */
{
"_id" : ObjectId("55d0996a331c571b60035d96"),
"title" : "zhangsan",
"comment" : [{
"author" : "joe",
"score" : 7
}, {
"author" : "suam",
"score" : 2
}, {
"author" : "jean",
"score" : 3
}]
}
/* 2 */
{
"_id" : ObjectId("55d099b1331c571b60035d97"),
"title" : "lisi",
"comment" : [{
"author" : "wangwu",
"score" : 4
}, {
"author" : "suam",
"score" : 8
}, {
"author" : "tom",
"score" : 6
}]
}
正确答案为
db.test.find({ "comment" : { "$elemMatch" : { "author" : "joe", "score" : { "$gte" : 5 } } } })db.test.find({ "comment" : { "author" : "joe", "score" : { "$gte" : 5 } } })来查询,那么内嵌文档的匹配必须要整个文档完全匹配。
如果使用
db.test.find({ "comment.author" : "joe", "comment.score" : { "$gt" : 5 } })那么符合auhor条件和符合score条件的评论可能不是同一条,也就是说会查询出以下两条文档
/* 0 */
{
"_id" : ObjectId("55d09915331c571b60035d95"),
"title" : "hello world",
"comment" : [{
"author" : "joe",
"score" : 3
}, {
"author" : "tom",
"score" : 5
}, {
"author" : "jean",
"score" : 9
}]
}
/* 1 */
{
"_id" : ObjectId("55d0996a331c571b60035d96"),
"title" : "zhangsan",
"comment" : [{
"author" : "joe",
"score" : 7
}, {
"author" : "suam",
"score" : 2
}, {
"author" : "jean",
"score" : 3
}]
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/zhaozonglu/article/details/47707973