MongoDB查询内嵌文档

本文演示了如何使用MongoDB查询特定作者和评分范围内的评论。通过使用$elemMatch和$gte操作符,可以精确筛选出符合条件的文档。文章详细解释了查询语法及其与直接查询的区别,帮助开发者高效地从数据库中检索所需信息。

有文档如下:

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值