如何使用 java 在 mongodb 中搜索文档并从中删除字段?

How to search a document and remove field from it in mongodb using java?

我有一个 device collection.

{
   "_id" : "10-100-5675234",
   "_type" : "Device",
   "alias" : "new Alias name", 
   "claimCode" : "FG755DF8N", 
   "hardwareId" : "SERAIL02",
   "isClaimed" : "true",
   "model" : "VMB3010", 
   "userId" : "5514f428c7b93d48007ac6fd" 
 }

我想通过 _id 搜索文档,然后在从结果文档中删除字段 userId 更新 它。我正在尝试不同的方法,但其中 none 有效。请帮助我。

一个丑陋的方法是用新版本的文档(没有用户标识)替换旧版本。

BasicDBObject newDocument = new BasicDBObject();
newDocument.put("_type", "Device");
newDocument.put("alias", "new Alias name");
// ...  

BasicDBObject searchQuery = new BasicDBObject().append("_id", "10-100-5675234");

collection.update(searchQuery, newDocument);

MongoDB 文档提供了一个 clear answer 这个问题:使用 $unset 更新运算符。

您可以使用 $unset 和 mongo-java 驱动程序删除字段,方法如下:

    MongoClient mongo = new MongoClient("localhost", 27017);
    DB db = (DB) mongo.getDB("testDB");
    DBCollection collection = db.getCollection("collection");
    DBObject query = new BasicDBObject("_id", "10-100-5675234");
    DBObject update = new BasicDBObject();
    update.put("$unset", new BasicDBObject("userId",""));
    WriteResult result = collection.update(query, update);
    mongo.close();

最简单的方法是使用 java 驱动程序中的功能:

Query query = new Query();
query.addCriteria(Criteria.where("_id").is(new ObjectId("10-100-5675234")));
Update update = new Update();
update.unset("userId"); //the fields you want to remove
update.set("putInYourFieldHere", "putInYourValueHere"); //the fields you want to add
mongoTemplate.updateFirst(query, update, Device.class);

上面的代码假设你的"_id"是你的mongodb正常"_id",这意味着你要查找的变量必须包含在new ObjectId()中。

这个 post 很久没打开了,但可能对以后的人有用。

device.updateMany(eq("_id", "whatever"), unset("userId"));