如何在mongodb中搜索嵌入式文档?

时间:2018-10-10 15:40:20

标签: mongodb aggregation-framework mongo-shell

我有这样的收藏

{
    "_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的favBook?

我现在正在尝试的是

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

这可能吗?

预先感谢:)

1 个答案:

答案 0 :(得分:1)

您可以尝试使用$unwind$replaceRoot

进行以下汇总
db.collection.aggregate([
  { "$match": { "favBooks.price": { "$lt": 400 }}},
  { "$unwind": "$favBooks" },
  { "$match": { "favBooks.price": { "$lt": 400 }}},
  { "$replaceRoot": { "newRoot": "$favBooks" }}
])