【问题标题】:How can I search for the embedded documents in mongodb?如何在 mongodb 中搜索嵌入的文档?
【发布时间】:2018-10-10 15:40:19
【问题描述】:

我有这样的收藏

{
    "_id" : ObjectId("5bbe1867839c0d2b4bdffcb2"),
    "name" : "Jyothish",
    "favBooks" : [
            {
                    "title" : "Let us C",
                    "author" : "Yaswanth Kanetkar",
                    "price" : 400
            },
            {
                    "title" : "Winner stands alone",
                    "author" : "Paulo Coelho",
                    "price" : 340
            }
    ]
}
{
    "_id" : ObjectId("5bbe1b62839c0d2b4bdffcb3"),
    "name" : "John",
    "favBooks" : [
            {
                    "title" : "Broken Republic",
                    "author" : "Arundhathi Roy",
                    "price" : 200
            },
            {
                    "title" : "One Life to Ride",
                    "author" : "Ajit Harisinghani",
                    "price" : 250
            }
    ]
}

有什么方法可以搜索价格低于 400 的收藏书籍?

我现在正在尝试的是

db.p.find({"favBooks.price":{$lt:400}}).pretty()

但这将返回所有文档中包含价格低于 400 的 favBook 项目。

我期望的输出是

{
        {
                "title" : "Winner stands alone",
                "author" : "Paulo Coelho",
                "price" : 340
        },
        {
                "title" : "Broken Republic",
                "author" : "Arundhathi Roy",
                "price" : 200
        },
        {
                "title" : "One Life to Ride",
                "author" : "Ajit Harisinghani",
                "price" : 250
        }
}

这可能吗?

提前致谢:)

【问题讨论】:

    标签: mongodb aggregation-framework mongo-shell


    【解决方案1】:

    您可以使用$unwind$replaceRoot 尝试以下聚合

    db.collection.aggregate([
      { "$match": { "favBooks.price": { "$lt": 400 }}},
      { "$unwind": "$favBooks" },
      { "$match": { "favBooks.price": { "$lt": 400 }}},
      { "$replaceRoot": { "newRoot": "$favBooks" }}
    ])
    

    【讨论】:

      猜你喜欢
      • 2021-06-03
      • 1970-01-01
      • 1970-01-01
      • 2011-05-24
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多