将多个文档合并到一个文档中,并且在MongoDB中具有两个文档字段 [英] merge multiple documents into one document with both document fields in MongoDB
本文介绍了将多个文档合并到一个文档中,并且在MongoDB中具有两个文档字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在MobgoDB中有多个文档如何对"abc"页面上的组执行操作和"xyz"并获得一份文件.请参见输出文件".需要与(文档1 U文档2)和(文档1 U文档3)进行合并.U =联盟
I have multiple documents In MobgoDB How to do to the group on "abc" and "xyz" and get one document. Please see the "Output Document". need to do the union with ( Document 1 U Document 2 ) and (Document 1 U Document 3) . U= Union
文档1
{
"data": {
"Inside_data": {
"project": {
"abc": {
"alpha": 4,
"beta" : 45
},
"xyz": {
"alpha": 214,
"beta" : 431
}
}
}
}
}
文档2
"Deal": {
"name": "abc",
"url" : "www.abc.com,
"email": [ "abc@gmail.com"],
"total": 2
}
文档3
"Deal": {
"name": "xyz",
"url" : "www.googl.com,
"email": [ "xyz@gmail.com"],
"total": 25
}
预期输出.
{
{
"name": "abc",
"url" : "www.abc.com,
"email": "abc@gmail.com",
"total": 2,
"alpha": 4,
"beta" : 45
},
{
"name": "xyz",
"url" : "www.googl.com,
"email": "xyz@gmail.com",
"total": 25,
"alpha": 214,
"beta" : 431
}
}
推荐答案
db.collection.aggregate([
{
$match: {
Deal: {
$exists: true
}
}
},
{
$lookup: {
from: "collection",
let: {
name: "$Deal.name"
},
pipeline: [
{
$match: {
data: {
$exists: true
}
}
},
{
$project: {
data: {
$reduce: {
input: {
$objectToArray: "$data.Inside_data.project"
},
initialValue: {},
in: {
$cond: [
{
$eq: [
"$$this.k",
"$$name"
]
},
"$$this.v",
"$$value"
]
}
}
}
}
},
{
$project: {
_id: 0,
alpha: "$data.alpha",
beta: "$data.beta"
}
}
],
as: "Deal.data"
}
},
{
$unwind: "$Deal.data"
}
])
@turivishal回答
Answer by @turivishal
这篇关于将多个文档合并到一个文档中,并且在MongoDB中具有两个文档字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文