码迷,mamicode.com
首页 > 数据库 > 详细

MongoDB查询内嵌文档

时间:2015-08-16 23:08:39      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:mongodb   查询内嵌文档   

有文档如下:

/* 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
    }]
}

请问如何查询author为joe,并且score为5以上的评论。

正确答案为

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
    }]
}



版权声明:本文为博主原创文章,未经博主允许不得转载。

MongoDB查询内嵌文档

标签:mongodb   查询内嵌文档   

原文地址:http://blog.csdn.net/zhaozonglu/article/details/47707973

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!