【问题标题】:Change document structure in mongodb with the mongo shell [duplicate]使用 mongo shell 更改 mongodb 中的文档结构 [重复]
【发布时间】:2016-05-27 15:09:31
【问题描述】:

我在 mongodb 中有一个文档结构,我想为我的所有文档更改它,而不使用像 response 这样的聚合函数,而是通过创建一个特定的函数,并从中得到结果:

{
"_id" : ObjectId("String"),
"content" : {
    "href" : "String",
    "text" : "String",
    "code" : "String "
}
}

到那个:

{
"_id" : ObjectId("String"),
"href" : "String",
"text" : "String",
"code" : "String "
}

请有任何建议。谢谢。

【问题讨论】:

    标签: mongodb mongo-shell


    【解决方案1】:

    如果您不喜欢聚合(或者您的 content 的内容可能因文档而异),您也可以使用

     db.coll.find().forEach(function (d) {
        db.coll.update({
            _id : d._id
        }, {
            $set : d.content,
            $unset : {
                'content' : 1
            }
        })
    });
    

    【讨论】:

      【解决方案2】:

      最简单的方法是使用聚合框架。 然后将输出保存到newCollection,验证后您可以删除旧的并重命名创建的。

      db.collection.aggregate([{
                  $project : {
                      _id : 1,    
                      href : "$content.href",
                      text : "$content.text",
                      code : "$content.code",    
                  }
              }, {
                  $out : "newCollection"
              }
          ])
      

      【讨论】:

      • 感谢您的回复,但实际上我想使用与之前回复类似的特殊功能。非常感谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-28
      • 1970-01-01
      • 2013-09-05
      • 2021-08-02
      相关资源
      最近更新 更多