我有这样的收藏
{
"_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
}
}
这可能吗?
预先感谢:)
答案 0 :(得分:1)
您可以尝试使用$unwind
和$replaceRoot
db.collection.aggregate([
{ "$match": { "favBooks.price": { "$lt": 400 }}},
{ "$unwind": "$favBooks" },
{ "$match": { "favBooks.price": { "$lt": 400 }}},
{ "$replaceRoot": { "newRoot": "$favBooks" }}
])