我有三个收集如下:
collectionA
:
_id: ObjectID('ID HERE'),
......
......
......
company: {
id: ObjectId('id of company'),
name: "Name of company"
},
conductors: [
{
name: "User1",
userId: ObjectId("id of user 1"),
_id: ObjectId('Id')
},
{
name: "New User", // This user is not existed in system, so only his/her name exists.
_id: ObjectId('id')
},
{
name: "User2",
userId: ObjectId("id of user 2"),
_id: ObjectId('Id')
},
]
company
收集是:
{
_id: ObjectId('company id'),
name: "company name",
......
......
}
和另一个集合user
:
{
_id: ObjectId('id of user'),
firstName: "User1",
profilePic: {
name: "",
size: ""
container: "",
.......
.......
}
}
我想要的是从collectionA
获取,并使用集合user
查找以获取用户的其他详细信息,例如profilePic
,但是对于用户表中不存在的新用户,以及字段userId
为空或不存在,我应该选择空profilePic
,我已经尝试使用$unwind
,但它只返回一个指挥(一个数组的elmenet)。
db.getCollection('collectionA').aggregate([
{"$match":{
"expireDate":{"$gt": ISODate("2018-03-31T04:35:43.693Z")},
"publishDate":{"$lt": ISODate("2018-04-02T00:00:00.000Z")},
"status":1
}},
{"$lookup":{
"from":"companies",
"localField":"company.id",
"foreignField":"_id",
"as":"companyDetails"
}},
{"$match":{"companyDetails":{"$ne":[]}}},
// {$unwind: "$conductors"},
// {
// $lookup:{
// from: "users",
// localField: "conductors.userId",
// foreignField: "_id",
// as: "conductorUsers"
// }
// },
// Unwind the result arrays ( likely one or none )
// { "$unwind": "$conductorUsers" },
// Group back to arrays
// { "$group": {
// "_id": "$_id",
// "conductors": { "$push": "$conductors" },
// "conductorUsers": { "$push": "$conductorUsers" }
// }},
{"$project":{
// "conductors": { "$push": "$conductors" },
// "conductorUsers": { "$push": "$conductorUsers" },
// "conductorUsers.firstName": 1,
// "conductorUsers.lastName": 1,
// "conductorUsers.profilePic": { $ifNull: [ "$conductorUsers.profilePic", "" ] },
// "conductorUsers._id": 1,
"title":1,
"description":1,
"startDate":1,"endDate":1,"publishDate":1,"expireDate":1,"type":1,
"location":1,"price":1,"contactNumbers":1,"emails":1,"link":1,
"conductors":1,"attachment":1,"company":1,"views":1,
"status":{"$cond":{
"if":{"$and":[
{"$lt":["$publishDate", ISODate("2018-04-02T00:00:00.000Z")]},
{"$gt":["$publishDate", ISODate("2018-03-31T00:00:00.000Z")]}
]},
"then":"New",
"else":{"$cond":{
"if":{
"$lt":["$publishDate", ISODate("2018-03-31T00:00:00.000Z")]
},"then":"Old","else":"Future"
}}
}},
"companyDetails.profilePic":1,"companyDetails.totalRatingAverage":1,
"companyDetails.name":1,"companyDetails.description":1,"companyDetails.website":1,
"companyDetails.founded":1,"companyDetails.benefits":1,
"expiringDuration":{"$floor":{
"$divide":[{"$subtract":["$expireDate", ISODate("2018-03-31T00:00:00.000Z")]},86400000]
}},
"companyDetails.totalReviews":{"$size":{"$ifNull":[
{"$let":{
"vars":{
"companyDetailOne":{"$arrayElemAt":["$companyDetails",0]}
},"in":"$$companyDetailOne.reviews"
}},[]
]}}
}}
])