我想找出如何做到以下几点:
目前,我使用以下脚本查看广告是否与列表匹配。
'$lookup': {
'from': 'advertisers',
'localField': 'title',
'foreignField': 'title',
'as': 'adsys'
}但是我们的一些列表中没有广告,当它正在返回时,它显示的是adsys:[]
相反,我希望它能显示adsys:NULL或完全删除adsys。我看过了
$ifNull但是,如果在查找中,我不确定如何将它附加到adsys上。
我试过这个:
{
'$lookup': {
'from': 'advertisers',
'localField': 'title',
'foreignField': 'title',
'as': 'adsys'
}
},
{
'$project': {
'title': 1,
'adsys': { '$ifNull': [ "$adsys", "Unspecified" ] }
}
}它还了这个:
{"data":[{"track":[{"_id":"5e1a96c3081a7a70d5c8971f","title":"Out of Mind","adsys":[]}]}]}我想做的是把这个还给你
{"data":[{"track":[{"_id":"5e1a96c3081a7a70d5c8971f","title":"Out of Mind","adsys":NULL}]}]}发布于 2020-01-12 04:47:28
在检查adsys的值后,可以使用$unwind关键字设置空值,如果未定义adsys,则可以设置空值。
db.tableName.aggregate(
[
{
'$lookup': {
'from': 'advertisers',
'localField': 'title',
'foreignField': 'title',
'as': 'adsys'
}
},
{ "$unwind": { path: "$adsys", preserveNullAndEmptyArrays: true } },
{
'$project': {
'title': 1,
'adsys': { '$ifNull': ["$adsys", "NULL"] }
}
}
]);发布于 2020-01-12 05:17:55
您可以尝试添加以下内容作为结束阶段:
{$project : {'title' :1, 'adsys' : {$cond : [{$gt:[{$size: '$adsys'}, 0]}, '$adsys' , null ] }}}因此,您的查询将是:
{
'$lookup': {
'from': 'advertisers',
'localField': 'title',
'foreignField': 'title',
'as': 'adsys'
}
}, { $project: { 'title': 1, 'adsys': { $cond: [{ $gt: [{ $size: '$adsys' }, 0] }, '$adsys', null] } } }**样本数据:**
/* 1 */
{
"_id" : ObjectId("5e1aa8d5627ef782369ef777"),
"title" : "Out of Mind",
"adsys" : []
}
/* 2 */
{
"_id" : ObjectId("5e1aa8e1627ef782369ef854"),
"title" : "Out of Mind",
"adsys" : [
{
"abc" : 1
}
]
}结果:
/* 1 */
{
"_id" : ObjectId("5e1aa8d5627ef782369ef777"),
"title" : "Out of Mind",
"adsys" : null
}
/* 2 */
{
"_id" : ObjectId("5e1aa8e1627ef782369ef854"),
"title" : "Out of Mind",
"adsys" : [
{
"abc" : 1
}
]
}https://stackoverflow.com/questions/59700778
复制相似问题