首页 > 数据库技术 > 详细

MongoDB查询内嵌文档

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

有文档如下:

/* 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查询内嵌文档

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!