我正在使用npm“csv-express”软件包将数据导出到CSV。我无法在导出的文件中显示嵌套的供应商名称。我使用$ lookup(聚合)从另一个集合中获取供应商名称。
这是我的问题:
db.getCollection('systems').aggregate([
{ "$sort": { "sponsor": 1 } },
{ "$lookup": {
"from": "vendors",
"localField": "vendorID",
"foreignField": "_id",
"as": "vendor"
}
},
{ "$project":{
"sponsor":1,
"address":1,
"city":1,
"state":1,
"vendor.name":1
}
}])
以下是查询返回的内容:
/* 1 */
{
"_id" : ObjectId("5ab55fee294f2366c054d5eb"),
"sponsor" : "John Doe",
"address" : "123 Western Ave",
"city" : "Los Angeles",
"state" : "CA",
"vendor" : [
{
"name" : "West Interactive"
}
]
}
我尝试了以下但没有运气。
db.getCollection('systems').aggregate([
{ "$sort": { "sponsor": 1 } },
{ "$lookup": {
"from": "vendors",
"localField": "vendorID",
"foreignField": "_id",
"as": "vendor"
}
},
{ "$project":{
"sponsor":1,
"address":1,
"city":1,
"state":1,
"vendor.[0].name":1
}
}])
任何建议都将不胜感激!
答案 0 :(得分:0)
我找到了一篇关于如何完成我所需要的文章。这是链接https://blog.couchbase.com/joining-nosql-documents-mongodb-query-language-vs-couchbase-n1ql/。希望这能帮到别人。
这是更新查询:
db.getCollection('systems').aggregate([
{ "$lookup": {
"from": "vendors",
"localField": "vendorID",
"foreignField": "_id",
"as": "vendor"
}
},
**{ $unwind: "$vendor" },**
{ "$project":{
"sponsor":1,
"address":1,
"city":1,
"state":1,
**"vendorName":"$vendor.name"**
}
}])
这返回了导出的数据需求。
/* 1 */
{
"_id" : ObjectId("5ab55fee294f2366c054d5eb"),
"sponsor" : "John Doe",
"address" : "123 Western Ave",
"city" : "Los Angeles",
"state" : "CA",
"vendorName" : "Acme Inc."
}