Mongodb 即使$lookup失败,也让聚合继续
我得到了一个长聚合,在这个聚合中是$lookup:Mongodb 即使$lookup失败,也让聚合继续,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我得到了一个长聚合,在这个聚合中是$lookup: { '$lookup': { from: 'users', localField: 'user', foreignField: '_id', as: 'users' } }, { '$unwind': '$users' }, 问题是,如果它没有在users中找到用户,那么它将跳过整个记录,并且不会在$project中返回任何内容 是否有一种方法可以执行“$lookup,如果失败,只需显示主记录” 以下是完整的汇总,以防万一: db.booki
{ '$lookup': { from: 'users', localField: 'user', foreignField: '_id', as: 'users' } },
{ '$unwind': '$users' },
问题是,如果它没有在users中找到用户,那么它将跳过整个记录,并且不会在$project中返回任何内容
是否有一种方法可以执行“$lookup,如果失败,只需显示主记录”
以下是完整的汇总,以防万一:
db.booking.aggregate([
{ '$match':
{
status: { '$in': [ 0, 1, 2, 3, 4, 5, 6, 9 ] },
'$or': [
{ checkin: { '$gte': 1516320000 }, checkout: { '$lte': 1521417600 } },
{ checkin: { '$lt': 1516320000 }, checkout: { '$gt': 1521417600 } },
{ checkin: { '$lt': 1516320000 }, checkout: { '$gt': 1516320000 } },
{ checkin: { '$lt': 1521417600 }, checkout: { '$gt': 1521417600 } }
]
}
},
{ '$sort': { checkin: 1 } },
{ '$lookup': { from: 'users', localField: 'user', foreignField: '_id', as: 'users' } }, { '$unwind': '$users' },
{ '$project': { _id: 1, property: 1, user: 1, name: '$users.name', country: '$users.country', checkin: 1, checkout: 1, priceNight: 1, status: 1, source: 1 } }
], {})
使用带有
$unwind
的选项保留行。类似于{'$unwind':{path:'$users',preserveNullandmptyarray:true}
。您可以重写聚合的最后一部分,以便在查找后仅使用project,而不使用$unwind STAGEVERAM!!你还在这里:D希望你能回答这个问题,呵呵。我在代码中得到一条评论说//Veeram说了一些关于保留空的东西。。。所以你以前可能帮过我。让我马上试试。确认<代码>{$lookup':{from:'users',localField:'user',foreignField:'u id',as:'users'},{$unwind':{path:'$users',preserveNullAndEmptyArrays:true}},工作得很好!!再次感谢Veeram:)@s7vr世界上应该有更多像你这样的男人。你救了我一天!!