[英]Checking 2 fields in array and combine two arrays to get single array Mongodb
I have a collection 我有一个收藏
{
_id:"123",
obj1:[{defaultNo:1,fine:100},{defaultNo:3,fine:10}],
obj2:[{default:1},{default:2},{default:3}]
}
I tried something like this but I was stuck 我尝试过类似的操作,但被卡住了
db.collection.aggregate([
// Match possible documents
{ "$match": {
"_id" : "123"
}},
{ "$unwind": "$obj1" },{
"$group": {
"_id": {
"document": "$_id",
"objfirst" : "$obj1.defaultNo",
"objlast":"$obj2"
},
} } ])
This gave me a result of 这给了我一个结果
"_id" : {
"document" : "123",
"objfirst" : "1",
"objlast" : [{default:1},{default:2},{default:3}]
}, "_id" : {
"document" : "123",
"objfirst" : "2",
"objlast" : [{default:1},{default:2},{default:3}]
},
But i was looking for this type of result like merging two arrays with the field values 但是我一直在寻找这种类型的结果,例如将两个数组与字段值合并
{
_id:"123",
object:[{default:1,fine100},{default:2,fine:false},{default:3,fine:10}]
}
I'd suggest you to look at $concatArrays
operator which do what exactly are you looking for. 我建议您看一下
$concatArrays
运算符,该运算符确实在寻找您想要的东西。
If you run following query in shell, 如果您在Shell中执行以下查询,
db.collection.aggregate([
{$match:{_id:"123"}},
{$project:{object:{$concatArrays:["$obj1","$obj2"]}}}
])
Output will be (matches closely your desired output using your sample input documents) 输出将是(使用样本输入文档与您期望的输出紧密匹配)
{
"_id" : "123",
"object" : [
{
"default" : 1.0,
"fine" : 100.0
},
{
"default" : 3.0,
"fine" : 10.0
},
{
"default" : 1.0
},
{
"default" : 2.0
},
{
"default" : 3.0
}
]
}
Update:
更新:
Added $match
to aggregation pipeline to match OP's attempt. 向聚合管道添加了
$match
以匹配OP的尝试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.