Mongodb Mongo聚合集合和项目字段
我有两个收藏 集合1模型:Mongodb Mongo聚合集合和项目字段,mongodb,mongodb-query,Mongodb,Mongodb Query,我有两个收藏 集合1模型: { "_id" : "abcdefgh", "questionType" : "multiselect", "question" : "how do you feel", "options" : [ { "option" : "Good ", "additionalTextRequired" : false }, {
{
"_id" : "abcdefgh",
"questionType" : "multiselect",
"question" : "how do you feel",
"options" : [
{
"option" : "Good ",
"additionalTextRequired" : false
},
{
"option" : "Bad",
"additionalTextRequired" : false
}
],
"active" : false,
}
集合2模型:
{
"_id" : "bhanu",
"someunrelatedfield":"dasf",
"responses" : [
{
"questionId" : "abcdefgh",
"response" : [
"Good"
],
"valid" : true,
"unrelatedfield":"dontprojectthese",
},
{
"questionId" : "someotherid",
"response" : [
"cool"
],
"valid" : true,
}
],
}
我想在查询后得到以下结果
{
"_id":"bhanu",
"responses":[
{
"question": "how do you feel",
"response": [
"good"
]
"valid":true,
}
]
}
基本上,我想在集合2中和项目指定的字段中将“questionId”替换为“question”。
如何为其编写查询?您需要使用$lookup
操作符执行以下操作:
db.collection2.aggregate([
{
$lookup: {
from: "collection1",
localField: "responses.questionId",
foreignField: "_id",
as: "tmp"
}
},
{
$addFields: {
responses: {
$map: {
input: "$responses",
as: "response",
in: {
$mergeObjects: [
"$$response",
{
$arrayElemAt: [
{
$filter: {
input: "$tmp",
cond: {
$eq: [
"$$response.questionId",
"$$this._id"
]
}
}
},
0
]
}
]
}
}
}
}
},
{
$unset: [
"responses.questionId"
//put here all fields to be removed
]
}
])
我已经用这种机制试过了。将创建一个新字段作为“响应”。我想回答的是一个领域内的问题和回答。对于mongo版本<4.2$unset不起作用,但是正常的预测是有效的<代码>{$project:{“_id”:1,“responses.question”:1,“responses.response”:1,}}@bhanu-Nice。实际上,使用
$project
可以排除字段