【问题标题】:How to change name of a field in MongoDB with java for each document in the collection?java - 如何使用java为集合中的每个文档更改MongoDB中字段的名称?
【发布时间】:2022-11-10 09:30:01
【问题描述】:

由于某些决定,我将不得不更改单个集合中所有文档中某些字段的名称。出于自动化测试的目的,我正在插入文档,然后检查一些逻辑。 让我们假设在插入方法之后我有以下对象:

    "_id" : ObjectId("60c10042d"),
    "Name" : Mike,
    "years" : 25,
    "Country" : England
},
{
    "_id" : ObjectId("40r10042t"),
    "Name" : Smith,
    "years" : 32,
    "Country" : England
}

插入文档/文档时,我想使用 Java 将字段“国家”更改为“职业”。这是我正在使用的代码示例:

MongoCollection<Document> documentMongo = MongoDb.getCollection("collectionName");
Document document = Document.parse(readJsonFile(json));

//I've tried this way:
//documentMongo.updateMany(document, Updates.rename("Country", "Occupation"));
//didn't work

documentMongo.insertOne(document);

【问题讨论】:

    标签: java json mongodb rename insert-update


    【解决方案1】:

    哦,重命名应该在插入完成之后。

    documentMongo.insertOne(document);
    documentMongo.updateMany(document, Updates.rename("Country", "Occupation"));
    
    Anyway, it could help others which are searching for easy way to change field names.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-04
      • 2020-09-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多