数据库结构:
db={
"collection": [
{
"key": 15,
"name": "srk",
},
{
"key": 12,
"name": "suman",
}
],
"other": [
{
"key": 15,
"name": "miki",
"category": "dish"
},
{
"key": 15,
"name": "mira",
"category": "air"
},
{
"key": 15,
"name": "manas",
"category": "air"
},
{
"key": 166,
"name": "sibu",
"category": "dish"
}
]
}
我正在尝试查询:
db.collection.aggregate([
{
$lookup: {
from: "other",
localField: "key",
foreignField: "key",
as: "inventory_docs"
}
},
{
$match: {
key: 15,
{ "inventory_docs":
{ category: 'dish'}
}
}
}
])
在mongodb中进行查询时,我没有得到结果。
请看看,告诉我查询中我做错了什么地方。
我将关键字与集合中的15个匹配,并将类别与国外集合中的“ Dish”匹配
答案 0 :(得分:0)
db.collection.aggregate([
{
$lookup: {
from: "other",
localField: "key",
foreignField: "key",
as: "inventory_docs"
}
},
{
$unwind: "$inventory_docs"
},
{
$match: {
key: 15,
"inventory_docs.category": "dish"
}
}
])
答案 1 :(得分:0)
尽管您已自行解决问题。 但是查询需要优化
如果您先执行“查找”,您将获得"key": 12
或所有其他键的数据。
只是为了优化查询:
db.collection.aggregate([
{
$match : { key: 15 }
},
{
$lookup: {
from: "other",
localField: "key",
foreignField: "key",
as: "inventory_docs"
}
},
{
$unwind: "$inventory_docs"
},
{
$match: {
"inventory_docs.category": "dish"
}
}
])