来自“房屋”系列
{
_id: "0",
rooms: [
{
roomName: "living-room"
chairs: "6"
},
{
roomName: "kitchen"
chairs: "0"
}
]
}
我需要找到_id = 0的房子,并且仅选择 来自“客厅”的“椅子”,结果如下:
{
chairs: 6
}
我想到的是这样的:
House.findOne({_id: '0'}).select('rooms.chairs') // but only from {roomName: "living-room"}
如何完成查询?
答案 0 :(得分:1)
这个怎么样?
db.houses.aggregate([
{ $match: { _id: "0" } },
{
$project: {
chairs: {
$filter: {
input: "$rooms",
cond: { $eq: ["$$this.roomName", "living-room"] }
}
}
}
},
{
$replaceRoot: {
newRoot: {
chairs: { $arrayElemAt: ["$chairs.chairs", 0] }
}
}
},
])
答案 1 :(得分:0)
db.house.findOne({"rooms.chairs":"6"},{"rooms.$":1})