如何在mongodb中重命名整个集合中的一个元素名称

时间:2018-03-26 12:03:39

标签: javascript node.js mongodb mongoose

我有一个像这样的猫鼬数据集:

{
    "_id" : ObjectId("5a8a91baec129c86c6a30cb6"),
    "sweet" : "APPLE",
    "price" : 27,
    "sellingprice" : 45
}...... like this I have 4000 entry with Different Fruit name.

出于某种原因,我必须改变" sweet"命名为" fruit"。 为此,我不知道如何更新All 4000条目。任何帮助都非常感谢。期望的结果将是:

{
    "_id" : ObjectId("5a8a91baec129c86c6a30cb6"),
    "fruit" : "APPLE",
    "price" : 27,
    "sellingprice" : 45
},
{
    "_id" : ObjectId("5a8a91baec129c86c6a30cb7"),
    "fruit" : "BANANA",
    "price" :48,
    "sellingprice" : 59
}and so on upto 3998 entry more.

我知道查询,其中任何内容都添加到整个列上,如下所示:

db.Collection.update({}, {$set: {'key': 'value'}}, false, true);

但对此没有任何线索。请提出一些好的方法

1 个答案:

答案 0 :(得分:4)

使用$rename

public class Subject {
   private List<Observer> observers = new ArrayList<Observer>();
   private int state;

   public void setState(int state) {
     this.state = state;
     notifyAllObservers();
   }

   public void notifyAllObservers(){
     for (Observer observer : observers) {
        observer.update();
     }
   }

   // [...omitted other unrelated methods...]
}
  • 首先检查db.Collection.update({'sweet': {$exists: true}}, {$rename:{'sweet':'fruit'}}, false, true); 字段是否存在
  • 然后重命名