我需要一种方法来为聚合管道中的文档数组中的每个文档添加属性。该属性的值来自数组中的值。我的集合中有这样的行:
{'a': 1, 'b': [{ 'this': 'A', 'that': 'B', 'other': 'C' }], 'c': 2},
{'a': 3, 'b': [{ 'this': 'D', 'that': 'E', 'other': 'F' }, {'this': 'G', 'that': 'H', 'other': 'I'}], 'c': 4}我希望将每个'b‘转换为具有两个属性'foo’和'bar‘的文档数组。“b”的每个元素都将变成“foo”。'bar‘的值是一个对象,其属性的值来自'foo’的'A‘属性。
我不想把结果写回集合中。
以下是我想要进行的转换:
{ "a" : 1, "b" : [ { "bar": { "this_value": "A"}, "foo" : { "this" : "A", "that" : "B", "other" : "C" } } ], "c" : 2 }
{ "a" : 3, "b" : [ { "bar": { "this_value": "D"}, "foo" : { "this" : "D", "that" : "E", "other" : "F" } }, { "bar" : { "this_value": "G" }, "foo" : { "this" : "G", "that" : "H", "other" : "I" } } ], "c" : 4 }在How to change elements of an array field to values of a dict with a single attribute in MongoDB 中,我学习了如何构造"foo“属性:
t.aggregate( [{$addFields: {'b': { $map: { input: '$b', in: {'foo': '$$this'}}}}} ] )我纠结于如何添加"bar“属性。
以下是创建我的集合和转换的"foo“部分的Mongo Shell命令:
c = new Mongo()
db = c.getDB('playful')
t = db['things']
t.insertMany([{'a': 1, 'b': [{ 'this': 'A', 'that': 'B', 'other': 'C' }], 'c': 2}, {'a': 3, 'b': [{ 'this': 'D', 'that': 'E', 'other': 'F' }, {'this': 'G', 'that': 'H', 'other': 'I'}], 'c': 4}])
t.aggregate( [{$addFields: {'b': { $map: { input: '$b', in: {'foo': '$$this'}}}}} ] )我在Ubuntu18.04上使用的是MongoDB 4.2.2。
发布于 2020-02-13 23:56:57
只需在foo中构造bar对象即可:
db.collection.aggregate([
{
$addFields: {
"b": {
$map: {
input: "$b",
in: {
"foo": "$$this",
"bar": {
this_value: "$$this.this"
}
}
}
}
}
}
])你可以在here上测试它
https://stackoverflow.com/questions/60211535
复制相似问题