2017-02-24 21 views
1

私はMongoDbの初心者ですが、2.xバージョンのコレクションを更新する例がたくさんありますが、3.xバージョンのソースは見つかりませんでした。JavaでMongoDbデータベースを更新するには?

Javaコード:

MongoClient mongoClient = new MongoClient("localhost",27017); 
    MongoDatabase database = mongoClient.getDatabase("dbTest"); 
    MongoCollection<Document> collection = database.getCollection("colTest"); 
    Document updateQuery = new Document(); 
    updateQuery.append("$set", 
    new Document().append("_id", "test")); 
    Document searchQuery = new Document(); 
    searchQuery.append("likes", "125"); 
    collection.updateMulti(searchQuery, updateQuery); //.updateMulti gives an error. 

任意のupdateMultiは、どのように私はデータベースのIDをチェックし、DATASの1つを変更することができますので、3.xのではありませんか?

例のMongoDB:

{ 
"_id" : "test", 
    "status" : 2, 
    "time" : null, 
    "instagram" :{ 
     "description" : "database", 
     "likes" : 100, 
     "url" : "http://www.instagram.com/", 
     "by", "users" 
    }, 
    "batchid" : 15000234 
} 

予想される出力:MongoDBの-javaのドライバの場合

{ 
    "_id" : "test", 
    "status" : 1, 
    "time" : null, 
    "instagram" :{ 
     "description" : "database", 
     "likes" : 125, 
     "url" : "http://www.instagram.com/", 
     "by", "users" 
    }, 
    "batchid" : 15000234 
} 

答えて

1

:フィルタに基づいて、コレクション内の単一のドキュメントを更新するには

使用updateOne方法 、

  collection.updateOne(searchQuery, updateQuery); 

フィルタに基づいて、コレクション内の複数のドキュメントを更新するために使用updateMany法、 、

  collection.updateMany(searchQuery, updateQuery); 

例、

 MongoClient client = new MongoClient("localhost",27017); 
     MongoDatabase db = client.getDatabase("TestDB"); 
     MongoCollection<Document> collection = db.getCollection("test"); 
     Document query = new Document(); 
     query.append("_id","test"); 
     Document setData = new Document(); 
     setData.append("status", 1).append("instagram.likes", 125); 
     Document update = new Document(); 
     update.append("$set", setData); 
     //To update single Document 
     collection.updateOne(query, update); 
関連する問題