MongoDB 聚合,使用一个文档中的值作为另一个文档中的键
MongoDB aggregation, use value from one document as key in another
因此,我尝试聚合两个在 id 上匹配并基于第一个文档的值的文档。
文档 1
{
“id”:3
“Whats for dinner”: “dinner”,
“What is for dinner tonight”: “dinner”,
“Whats for lunch”:“lunch”
}
文件 2
{
“Id”:3
“dinner” : “We are having roast!”,
“lunch” : “We are having sandwiches”
}
我想从匹配 id 开始,测试 doc1 中是否存在问题。
然后 return 来自 doc1 的问题和来自 doc 2 的答案。喜欢
{“Whats for dinner”:“We are having roast!”}
我试过:
{ “$match”: { “id”: 3, “Whats for dinner”:{"$exists":True}} },
{
"$lookup": {
"from": "doc 2",
"localField": "id",
"foreignField": "id",
"as": "qa"
}
}
但是从这里我无法弄清楚如何将 doc1 中的值用作 doc2 中的键
可能很简单!但我是新手,就是无法让它工作!?
疯狂的数据模型!这将是一个解决方案:
db.doc1.aggregate([
{ $project: { data: { $objectToArray: "$$ROOT" } } },
{ $unwind: "$data" },
{
$lookup: {
from: "doc2",
pipeline: [
{ $project: { data: { $objectToArray: "$$ROOT" } } }
],
as: "answers"
}
},
{
$set: {
answers: {
$first: {
$filter: {
input: { $first: "$answers.data" },
cond: { $eq: [ "$$this.k", "$data.v" ] }
}
}
}
}
},
{ $match: { answers: { $exists: true } } },
{
$project: {
data: [
{
k: "$data.k",
v: "$answers.v"
}
]
}
},
{ $replaceWith: { $arrayToObject: "$data" } }
])
最好不要使用任何用户数据作为键名,您将始终需要兼顾 $objectToArray
和 $arrayToObject
也许可以考虑一下:
questions: {
guildid: 3,
text: [
"Whats for dinner",
"What is for dinner tonight",
"Whats for lunch"
],
"nospace": 1
}
因此,我尝试聚合两个在 id 上匹配并基于第一个文档的值的文档。
文档 1
{
“id”:3
“Whats for dinner”: “dinner”,
“What is for dinner tonight”: “dinner”,
“Whats for lunch”:“lunch”
}
文件 2
{
“Id”:3
“dinner” : “We are having roast!”,
“lunch” : “We are having sandwiches”
}
我想从匹配 id 开始,测试 doc1 中是否存在问题。 然后 return 来自 doc1 的问题和来自 doc 2 的答案。喜欢
{“Whats for dinner”:“We are having roast!”}
我试过:
{ “$match”: { “id”: 3, “Whats for dinner”:{"$exists":True}} },
{
"$lookup": {
"from": "doc 2",
"localField": "id",
"foreignField": "id",
"as": "qa"
}
}
但是从这里我无法弄清楚如何将 doc1 中的值用作 doc2 中的键
可能很简单!但我是新手,就是无法让它工作!?
疯狂的数据模型!这将是一个解决方案:
db.doc1.aggregate([
{ $project: { data: { $objectToArray: "$$ROOT" } } },
{ $unwind: "$data" },
{
$lookup: {
from: "doc2",
pipeline: [
{ $project: { data: { $objectToArray: "$$ROOT" } } }
],
as: "answers"
}
},
{
$set: {
answers: {
$first: {
$filter: {
input: { $first: "$answers.data" },
cond: { $eq: [ "$$this.k", "$data.v" ] }
}
}
}
}
},
{ $match: { answers: { $exists: true } } },
{
$project: {
data: [
{
k: "$data.k",
v: "$answers.v"
}
]
}
},
{ $replaceWith: { $arrayToObject: "$data" } }
])
最好不要使用任何用户数据作为键名,您将始终需要兼顾 $objectToArray
和 $arrayToObject
也许可以考虑一下:
questions: {
guildid: 3,
text: [
"Whats for dinner",
"What is for dinner tonight",
"Whats for lunch"
],
"nospace": 1
}