viv*_*k85 4 mongodb mongodb-java mongodb-query
我正在尝试更新 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 的相同字段,但不确定为什么这不起作用。有什么想法吗?
尝试使用以下配置,我的代码中有一些编译错误,我在下面修复了这些错误。
public class StackOverflowApp {
public static void main (String[] args){
MongoClientOptions options = MongoClientOptions.builder().connectionsPerHost(100).build();
MongoClient client = new MongoClient(new ServerAddress(), options);
MongoDatabase db = client.getDatabase("test").withReadPreference(ReadPreference.secondary());
String userId = "myUser2";
String fileType = "fileType2";
String fileName = "fileName";
String fileSize = "fileSize";
MongoCollection<Document> docs = db.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 Date(System.currentTimeMillis())));
((Document)updateQuery).append("$setOnInsert", new Document("creationTimestamp", new Date(System.currentTimeMillis())));
docs.updateOne(filterQuery, updateQuery, (new UpdateOptions()).upsert(true));
}
}
Run Code Online (Sandbox Code Playgroud)
如果我第一次运行我插入这个。
"_id" : ObjectId("570c6f2105c7937ac1c794cb"),
"fileType" : "fileType2",
"userId" : "myUser2",
"fileName" : "fileName",
"fileSize" : "fileSize",
"lastModifiedTimestamp" : ISODate("2016-04-12T03:44:33.454Z"),
"creationTimestamp" : ISODate("2016-04-12T03:44:33.454Z")
Run Code Online (Sandbox Code Playgroud)
第二次仅更新lastModifiedTimestamp
"_id" : ObjectId("570c6f2105c7937ac1c794cb"),
"fileType" : "fileType2",
"userId" : "myUser2",
"fileName" : "fileName",
"fileSize" : "fileSize",
"lastModifiedTimestamp" : ISODate("2016-04-12T03:44:59.947Z"),
"creationTimestamp" : ISODate("2016-04-12T03:44:33.454Z")
Run Code Online (Sandbox Code Playgroud)
我认为这就是你试图实现的目标。
| 归档时间: |
|
| 查看次数: |
6338 次 |
| 最近记录: |