人员集合:
[
{
"_id": ObjectId("5f3258cfbaaccedaa5dd2c96"),
"gender": "male",
"name": {
"title": "mr",
"first": "victor",
"last": "pedersen"
},
"location": {
"street": "2156 stenbjergvej",
"city": "billum",
"state": "nordjylland",
"postcode": 56649
},
"email": "[email protected]"
}
]
PersonDetails集合:
{
"_id": ObjectId("5f3a91e68b1c26e68f9ed3ad"),
"country": "India",
"personid": ObjectId("5f3258cfbaaccedaa5dd2c96")
}
CountryDetails集合:
{
"_id": ObjectId("5f3fc2aa9532398a037ff7ae"),
"country": "India",
"continent": "Asia"
}
假设1个人可以有很多个人详细信息,而1个人可以有很多国家/地区详细信息。
查询:获取大陆为亚洲的人员,人员详细信息和国家/地区详细信息。
结果应如下所示:
[{
"_id": ObjectId("5f3258cfbaaccedaa5dd2c96"),
"gender": "male",
"name": {
"title": "mr",
"first": "victor",
"last": "pedersen"
},
"location": {
"street": "2156 stenbjergvej",
"city": "billum",
"state": "nordjylland",
"postcode": 56649
},
"email": "[email protected]",
"persondetail": [{
"_id": ObjectId("5f3a91e68b1c26e68f9ed3ad"),
"country": "India",
"personid": "5f3258cfbaaccedaa5dd2c96",
"countrydetail": [{
"_id": ObjectId("5f3fc2aa9532398a037ff7ae"),
"country": "India",
"continent": "Asia"
}]
}]
}]
注意:必须与aggregate()一起使用
我的失败尝试:
db.persons.aggregate([
{
"$match": {
"$expr": {
"$eq": [
"$_id",
{
"$toObjectId": "5f3258cfbaaccedaa5dd2c96"
}
]
}
}
},
{
$lookup: {
from: "persondetails",
localField: "_id",
foreignField: "personid",
as: "persondetail"
}
},
{
$unwind: {
"path": "$persondetail",
includeArrayIndex: "arrayIndex",
preserveNullAndEmptyArrays: true
}
},
{
$lookup: {
from: "country",
localField: "persondetail.country",
foreignField: "country",
as: "countrydetails"
}
},
{
"$match": {
"$expr": {
"$eq": [
"$persondetail.continent",
"Asia"
]
}
}
}
])
上面的查询不起作用,即使它起作用了,unwind
也会给我一个扁平的结构。这与我要寻找的相反。
您可以使用$ lookup和自定义管道来嵌套查询:
{
$lookup: {
from: "persondetails",
let: { person_id: "$_id" },
pipeline: [
{
$match: {
$expr: { $eq: [ "$personid", "$$person_id" ] }
}
},
{
$lookup: {
from: "countrydetails",
localField: "country",
foreignField: "country",
as: "countrydetail",
}
}
],
as: "persondetail"
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句