我正在尝试更新 mongodb 中的集合,如果字段存在,将插入它。我不太确定如何使用 upsert 选项来做到这一点。
MongoCollection<Document> docs = mongoDb.getCollection("users");
Bson filterQuery = new Document("userId", userId).append("fileType", fileType);
Bson updateQuery = new Document("$set", new Document("fileType", fileType).append("fileName", fileName).append("fileSize", fileSize).append("userId", userId).append("lastModifiedTimestamp", new Timestamp(System.currentTimeMillis())));
updateQuery.append("$setOnInsert", new Document("creationTimestamp", new Timestamp(System.currentTimeMillis())));
docs.updateOne(filterQuery, updateQuery, (new UpdateOptions()).upsert(true));
Run Code Online (Sandbox Code Playgroud)
这是行不通的。我没有更新 $set 和 $setOnInsert 的相同字段,但不确定为什么这不起作用。有什么想法吗?