Javascript MongoDB-如何仅在存在的字段上使用$ifNull
我正在使用Javascript MongoDB-如何仅在存在的字段上使用$ifNull,javascript,mongodb,Javascript,Mongodb,我正在使用$lookup,它可能返回或不返回某些内容。但是如果它是空的,我需要检查查找的值并检查一个特定的字段以查看它是否为空,如果为空,则将其设置为某个值 我试过这个: { $lookup: { from: "item_templates", localField: "based_on", foreignField: "_id", as:
$lookup
,它可能返回或不返回某些内容。但是如果它是空的,我需要检查查找的值并检查一个特定的字段以查看它是否为空,如果为空,则将其设置为某个值
我试过这个:
{
$lookup:
{
from:
"item_templates",
localField:
"based_on",
foreignField:
"_id",
as:
"template"
}
},
{
$addFields:
{
"template.image.url":
{
$ifNull:
[
"$template.image.url",
"http://via.placeholder.com/400x700/d3d3d3/000000/?text=No%20Image&"
]
}
}
},
但它似乎对
template.image.url
(这是一个对象数组)没有影响,它实际上返回一个数组,其中一个元素为null
请尝试使用$project
{
$unwind:{
path: "$template",
includeArrayIndex: "arrayIndex",
preserveNullAndEmptyArrays: true
}
},
{
$project:{
template.image.url: {
$ifNull: [
"$template.image.url",
"http://via.placeholder.com/400x700/d3d3d3/000000/?text=No%20Image&"
]
},
}
}
您可以使用更新的
$lookup
语法来实现预期的结果
db.collection.aggregate([
{ "$lookup": {
"from": "item_templates",
"let": { "based_on": "$based_on" },
"pipeline": [
{ "$match": { "$expr": { "$eq": ["$_id", "$$based_on"] }}},
{ "$addFields": {
"image.url": {
"$ifNull": [
"$image.url",
"http://via.placeholder.com/400x700/d3d3d3/000000/?text=No%20Image&"
]
}
}}
],
"as": "template"
}}
])
仍然将其转换为一个数组,其中一个元素为
null
。此外,该项目还去掉了所有其他字段,这是不可取的。在$project之前,也要展开模板。答案一如既往。