运维开发网

MongoDB查询内嵌文档

运维开发网 https://www.qedev.com 2020-03-04 09:36 出处:网络 作者:运维开发网整理
有文档如下: /* 0 */ { "_id" : ObjectId("55d09915331c571b60035d95"), "title" : "hello world", "comment" : [{ "author" : "joe", "score" : 3 }, { "author" : "tom", "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
    }]
}

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

精彩评论

暂无评论...
验证码 换一张
取 消