我正在尝试在管道阶段合并位于嵌入式文档集合中的两个数组字段。但是我坚持如何引用嵌入式文档的两个“内部”数组。
[{
name: "first",
docs: [
{ a1: ["a", "b"], a2: ["c"] },
{ a1: ["d", "e"], a2: ["f"] }
]
},
{
name: "second",
docs: [
{ a1: [1, 2], a2: [3] },
{ a1: [4, 5], a2: [6] }
]
}]
[{
name: "first",
docs: [
{ merged: ["a", "b", "c"] },
{ merged: ["d", "e", "f"] }
]
},
{
name: "second",
docs: [
{ merged: [1, 2, 3] },
{ merged: [4, 5, 6] }
]
}]
到目前为止,我尝试的总体方法是:(具有2个硬编码数组用于测试目的)
db.getCollection("collection").aggregate([{
$set: {
"docs.merged": {
$concatArrays: [["hello"], ["world"]]
}
}
}])
产生预期的结果:
[{
name : "first",
docs : [
{
a1 : ["a", "b"],
a2 : ["c"],
merged : ["hello", "world"] // <- OK
},
{
a1 : ["d", "e"],
a2 : ["f"],
merged : ["hello", "world"] // <- OK
}
]
},{
name : "second",
docs : [
{
a1 : [1.0, 2.0],
a2 : [3.0],
merged : ["hello", "world"] // <- OK
},
{
a1 : [4.0, 5.0],
a2 : [6.0],
merged : ["hello", "world"] // <- OK
}
]
}]
但是我很难理解如何引用当前嵌入式文档中的字段:
// Using the "$" reference causes following error:
// Invalid $set :: caused by :: FieldPath field names may not start with '$'.
{
$set: {
"docs.merged": { $concatArrays: ["$docs.$.a1", "$docs.$.a2"] }
}
}
// $$this is only available with a MAP operator
{
$set: {
"docs.merged": { $concatArrays: ["$$this.a1", "$$this.a2"] }
}
}
我不能使用update
查询,因为不得更改原始文档。因此,这必须在aggregate
管道中实现。
unwind
在这一点上,我尝试避免使用操作,因为这会对性能产生重大影响。在实际的文件中含有相当多的(变量)字段中的它的根; group
在unwind
相当复杂的阶段之后登台表演。(示例已大大简化了可读性)
我正在使用MongoDB v4.4
。
我想这样做会成功,请让我知道我是否缺少任何东西:
db.collection.aggregate([{
$project: {
_id: 0,
"name": 1,
"docs": {
$function: {
body: function(docs) {
docs.forEach(function(doc) {
var merged = [];
Object.keys(doc).forEach(function(k) {
merged = merged.concat(doc[k]);
delete doc[k];
});
doc.merged = merged;
});
return docs;
},
args: [ "$docs" ],
lang: "js"
}
}
}
}])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句