首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为数组中的每个文档添加属性的管道

为数组中的每个文档添加属性的管道
EN

Stack Overflow用户
提问于 2020-02-13 23:40:15
回答 1查看 179关注 0票数 0

我需要一种方法来为聚合管道中的文档数组中的每个文档添加属性。该属性的值来自数组中的值。我的集合中有这样的行:

代码语言:javascript
复制
{'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‘属性。

我不想把结果写回集合中。

以下是我想要进行的转换:

代码语言:javascript
复制
{ "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“属性:

代码语言:javascript
复制
t.aggregate( [{$addFields: {'b': { $map: { input: '$b', in: {'foo': '$$this'}}}}} ] )

我纠结于如何添加"bar“属性。

以下是创建我的集合和转换的"foo“部分的Mongo Shell命令:

代码语言:javascript
复制
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。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-13 23:56:57

只需在foo中构造bar对象即可:

代码语言:javascript
复制
db.collection.aggregate([
  {
    $addFields: {
      "b": {
        $map: {
          input: "$b",
          in: {
            "foo": "$$this",
            "bar": {
              this_value: "$$this.this"
            }
          }
        }
      }
    }
  }
])

你可以在here上测试它

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60211535

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档