gpt4 book ai didi

node.js - 如果不存在,MongoDB 将默认值合并到每个文档

转载 作者:搜寻专家 更新时间:2023-10-30 20:33:29 25 4
gpt4 key购买 nike

我有两个集合 students 和 countries,countries 集合有一些默认值,我想通过 MongoDB 查询将 countries 默认值合并到 students 集合

学生收集一些文件

[
{
"name": "John"
},
{
"name": "Tom"
},
{
"name": "Harry",
"country": {
"AUS": 150
}
}
]

国家收集一些文件

[{
"name": "AUS",
"value": 100
},
{
"name": "CAN",
"value": 200
}]

对于学生集合国家可能存在也可能不存在

现在我想在 MongoDB 中编写一个查询,它将使用学生和国家集合返回以下文档

[
{
"name": "John",
"country": {
"AUS": 100,
"CAN": 200
}
},
{
"name": "Tom",
"country": {
"AUS": 100,
"CAN": 200
}
},
{
"name": "Harry",
"country": {
"AUS": 150,
"CAN": 200
}
}
]

如果学生集合中存在国家值,那么它将从那里获取该国家值,并从国家集合中获取其余值,例如学生“Harry”中给出的示例如果学生中没有国家值,那么我们将从国家集合中获取所有默认值。

感谢任何帮助,如果需要,我们可以重新设计学生和国家/地区集合。MongoDB单查询不可以吗,是否需要在NodeJS应用中写一些自定义代码

最佳答案

您可以使用 $lookup with custom pipeline将所有国家/地区数据从 students 集合中获取到文档中,然后您需要使用 $objectToArray$arrayToObject动态生成 contry 对象的键和值。由于来自 country 的数据是 $concatArrays 的第一个参数它将覆盖默认值

db.students.aggregate([
{
$lookup: {
from: "countries",
pipeline: [ { $project: { _id: 0, k: "$name", v: "$value" } } ],
as: "countries"
}
},
{
$project: {
name: 1,
country: {
$arrayToObject: {
$concatArrays: [ { $ifNull: [ { $objectToArray: "$country" }, [] ] }, "$countries" ]
}
}
}
}
])

关于node.js - 如果不存在,MongoDB 将默认值合并到每个文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55575549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com