English 中文(简体)
将文件实地命名,并在Aggregation中将其列为空地
原标题:Getting the document field names and adding them as nested fields in an Aggregation
  • 时间:2023-12-13 02:43:33
  •  标签:
  • mongodb

Im writing a mongodb aggregate pipeline. My documents are of the form below :

   {
  name: "01"
  tags {
  tag_01: {
    a: "a01-val",
    b: "b01-val"
  },
  tag_02: {
    a: "a02-val",
    b: "b02-val"
  }
  }
},
{
  name: "02"
  tags {
  tag_03: {
    a: "a03-val",
    b: "b03-val"
  },
  tag_04: {
    a: "a04-val",
    b: "b04-val"
  }
  }
}

我的管道应当产生以下文件:

{
  name: "01"
  tags {
  tag_01: {
    a: "a01-val",
    b: "b01-val",
    tagName: "tag_01"
  },
  tag_02: {
    a: "a02-val",
    b: "b02-val",
    tagName: "tag_02"
  }
  }
},
{
  name: "02"
  tags {
  tag_03: {
    a: "a03-val",
    b: "b03-val",
    tagName: "tag_03"
  },
  tag_04: {
    a: "a04-val",
    b: "b04-val",
    tagName: "tag_04"
  }
  }
}

In other words, a new field is added inside each subdocument whose value is the name of the parent field. Is it possible to do this?

问题回答

使用<代码>$object ToArray,将tags转换成一系列k-v tuples。 使用<条码> 地图,通过阵列元素和<条码>,将现场定位为<条码>k。 然后使用<代码>$array ToObject,以重回原物体表格。

db.collection.update({},
[
  {
    "$set": {
      "tags": {
        "$objectToArray": "$tags"
      }
    }
  },
  {
    "$set": {
      "tags": {
        "$map": {
          "input": "$tags",
          "as": "tag",
          "in": {
            k: "$$tag.k",
            v: {
              "$mergeObjects": [
                "$$tag.v",
                {
                  "tagName": "$$tag.k"
                }
              ]
            }
          }
        }
      }
    }
  },
  {
    $set: {
      tags: {
        "$arrayToObject": "$tags"
      }
    }
  }
],
{
  multi: true
})

Mongo 游乐场





相关问题
Access DB Ref MongoDB

Whats the best way to access/query a DB Ref: UPDATE: users: name, groupref : {$ref:"groups",$id:"ObjectId ..." } } groups: name, topic, country,...,.. Assumption is that user belongs to only one ...

MongoDB nested sets

What re the best practices to store nested sets (like trees of comments) in MongoDB? I mean, every comment can have a parent comment and children-comments (answers). Storing them like this: { ...

MongoMapper and migrations

I m building a Rails application using MongoDB as the back-end and MongoMapper as the ORM tool. Suppose in version 1, I define the following model: class SomeModel include MongoMapper::Document ...

MongoDB takes long for indexing

I have the following setup: Mac Pro with 2 GB of RAM (yes, not that much) MongoDB 1.1.3 64-bit 8 million entries in a single collection index for one field (integer) wanted Calling .ensureIndex(...) ...

Storing and accessing large amounts of data

My application creates pieces of data that, in xml, would look like this: <resource url="someurl"> <term> <name>somename</name> <frequency>somenumber</...

热门标签