复制并重命名 MongoDB 中的文档字段 [英] Copy and rename a document field in MongoDB

查看:56
本文介绍了复制并重命名 MongoDB 中的文档字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重命名我的 Mongo 集合中所有文档都有的字段.已经有一个很好的答案.但我不想覆盖当前的属性名称,而是想将重命名的属性保存为新字段,保持原始属性不变.

I want to rename a field that all documents have in my Mongo collection. There's already a great answer for that. But instead of overwriting the current property name, I want to save my renamed property as a new field, leaving the original intact.

想象一下我的文档是这样的:

Imagine my documents look like this:

{
  "property": "Original property value"
}

我想得到这个:

{
  "property": "Original property value",
  "property_new": "Original property value"
}

我该怎么做?

推荐答案

您可以使用 $out 聚合

db.collection.find([
  { "$addFields": {
    "property_new": "$property"
  }},
  { "$out": "newCollection" }
])

它将创建一个名为 newCollection 的新集合,只需将其重命名为现有集合即可.

It will create a new collection with the name newCollection just rename it with the existing one.

这篇关于复制并重命名 MongoDB 中的文档字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆