2016-04-12 6 views
2

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)); 

これは機能しません。私は$ setと$ setOnInsertの同じフィールドを更新していませんが、なぜこれが動作していないのか分かりません。何かご意見は?

+0

更新を行うたびにlastModifiedTimestampを更新しようとしていますか、それとも達成しようとしていますか?私はレコードが存在していない場合は、あなたがlastModifiedTimestampを更新しようとするレコードが存在する場合は、私は正しいと、creationTimestampを挿入しようとしていると思いますか? – Koitoer

+0

はい、正確です。更新を行うたびにlastModifiedTimestampを更新しようとしています。 – vivek85

答えて

2

次の設定を使用しようとしましたが、私はあなたのコードに次のようにいくつかのコンパイルエラーがあります。

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)); 
    } 
} 

初めて実行する場合は、このファイルを挿入します。

"_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") 

二時間だけ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") 

に更新され、私はそれはあなたが達成しようとしていたものだと思います。

+0

java.util.Dateを使用しましたか?何らかの理由でタイムスタンプを保存できません。 – vivek85

+0

それは今働いています。輸入に関するいくつかの問題がありました。 – vivek85

関連する問題