我需要在数组 [1, 2, 3, 4, 5] 中选择 id
,
如果没有 ID 为 3 和 5
的文档,我需要默认名称。
例如。
{id:1,name:a}
{id:2,name:b}
{id:4,name:c}
查询某事...
find ... id:{$in:{1,2,3,4,5}}})
-> 结果应该是
{id:1,name:a}
{id:2,name:b}
{id:3,name:defaultvalue}
{id:4,name:c}
{id:5,name:defaultvalue}
我想要 3 和 5 的默认值。
我该如何查询?? 请帮忙
最佳答案
您可以使用 MongoDB aggregation framework 实现您的用例
- 我从 $facet 开始并创建了两个数组:
missingIDs
找出文档中不存在的缺失 IDmatchedDocuments
到 $project数组 [1,2,3,4,5] 中可用的所有可用文档
- 然后连接这两个数组,并使用$addFields连同 $ifNull如果为空,则添加名称字段。
尝试以下聚合查询:
db.collection.aggregate([
{
$facet: {
missingIDs: [
{
$group: {
_id: null,
ids: {
$push: {
id: "$id"
}
}
}
},
{
$project: {
_id: 0,
ids: {
$setDifference: [
[
{
id: 1
},
{
id: 2
},
{
id: 3
},
{
id: 4
},
{
id: 5
}
],
"$ids"
]
}
}
},
{
$unwind: "$ids"
},
{
$project: {
id: "$ids.id"
}
}
],
matchedDocuments: [
{
$match: {
id: {
$in: [
1,
2,
3,
4,
5
]
}
}
},
{
$project: {
id: 1,
name: 1,
_id: 0
}
}
]
}
},
{
"$project": {
concat: {
"$concatArrays": [
"$matchedDocuments",
"$missingIDs"
]
}
}
},
{
$unwind: "$concat"
},
{
"$addFields": {
"concat.name": {
"$ifNull": [
"$concat.name",
"defaultvalue"
]
}
}
},
{
$project: {
id: "$concat.id",
name: "$concat.name",
}
},
{
"$sort": {
id: 1
}
}
])
关于文档不在数组中的mongodb默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64380420/