我有4个收藏:人,公司,城市和国家.
人物收藏:
[
{_id: 1, name: "Mario", surname: "Rossi", company: 2, city: 3, nation: 4},
{_id: 2, name: "Steve", surname: "Red", company: 2},
{_id: 3, name: "Alan", surname: "Joe", city: 3},
{_id: 4, name: "Mark", surname: "Bill", nation: 2},
{_id: 5, name: "John", surname: "Cena", company: 1, city: 3},
{_id: 6, name: "Frank", surname: "Avrett", company: 2, nation: 5},
{_id: 7, name: "Anne", surname: "Swander", nation: 3, city: 8}
]
Run Code Online (Sandbox Code Playgroud)
公司,城市和国家馆藏只有_id和名称栏.
我想要一份包含公司,城市和国家名称的所有人的列表.
如果记录没有得到id公司或城市或国家我想要一个空场.
var aggregate = this.aggregate([
{
$lookup: {
from: "company",
localField: "company",
foreignField: "_id",
as: "x"
}
},
{
$lookup: {
from: "city",
localField: "city",
foreignField: "_id",
as: "y"
}
},
{
$lookup: {
from: "nation",
localField: "nation",
foreignField: "_id",
as: "z"
}
}
,{ $unwind: "$x" }
,{ $unwind: "$y" }
,{ $unwind: "$z" }
,{ $project : { _id:1, name:1, surname:1, nation:1, company:1, city:1, companyName: "$x.name", cityName: "$y.name", nationName: "$z.name" } }
,{ $sort: {name:1} }
]);
Run Code Online (Sandbox Code Playgroud)
此查询返回:
[{_id: 1, name: "Mario", surname: "Rossi", company: 2, city: 3, nation: 4, companyName: "Google", cityName: "New York", nationName: "United States" }]
Run Code Online (Sandbox Code Playgroud)
仅包含所有3个引用与其他集合的记录.
我怎么能拥有所有人?
Cle*_*ath 12
使用$ unwind时,聚合管道中的空数据和空数据将丢失.将其添加 "preserveNullAndEmptyArrays": true到$ unwind部分.
修改查询
var aggregate=this.aggregate([
{
$lookup: {
from: "company",
localField: "company",
foreignField: "_id",
as: "x"
}
},
{
$lookup: {
from: "city",
localField: "city",
foreignField: "_id",
as: "y"
}
},
{
$lookup: {
from: "nation",
localField: "nation",
foreignField: "_id",
as: "z"
}
},
{
$unwind: {
path: "$x",
"preserveNullAndEmptyArrays": true
}
},
{
$unwind: {
path: "$y",
"preserveNullAndEmptyArrays": true
}
},
{
$unwind: {
path: "$z",
"preserveNullAndEmptyArrays": true
}
},
{
$project: {
_id: 1,
name: 1,
surname: 1,
nation: 1,
company: 1,
city: 1,
companyName: "$x.name",
cityName: "$y.name",
nationName: "$z.name"
}
},
{
$sort: {
name: 1
}
}
]);
Run Code Online (Sandbox Code Playgroud)
需要修改数据库模式,因为它类似于RDBMS世界中的精确规范化表.MongoDB是一个NoSQL数据库,在这个给定的公司,城市和国家集合的场景中只有_id,我会选择将所有这些集合合并到一个集合中的模式.