Java MongoDB: document de mise à jour
Dans ce didacticiel, nous vous montrons comment utiliser l'API Java MongoDBcollection.update()
pour mettre à jour des documents.
Données de test
Supposons que les données / documents suivants soient insérés.
{ "hosting" : "hostA", "type" : "vps", "clients" : 1000 }, { "hosting" : "hostB", "type" : "dedicated server", "clients" : 100 }, { "hosting" : "hostC", "type" : "vps", "clients" : 900 }
{ "_id" : { "$oid" : "id"} , "hosting" : "hostA" , "type" : "vps" , "clients" : 1000} { "_id" : { "$oid" : "id"} , "hosting" : "hostB" , "type" : "dedicated server" , "clients" : 100} { "_id" : { "$oid" : "id"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900}
1. DBCollection.update() with $set
Recherchez le document où hosting = ‘hostB’ et mettez à jour les valeurs des clients de 100 à 110.
BasicDBObject newDocument = new BasicDBObject(); newDocument.put("clients", 110); BasicDBObject searchQuery = new BasicDBObject().append("hosting", "hostB"); collection.update(searchQuery, newDocument);
Sortie
{ "_id" : { "$oid" : "id"} , "hosting" : "hostA" , "type" : "vps" , "clients" : 1000} { "_id" : { "$oid" : "id"} , "clients" : 110} { "_id" : { "$oid" : "id"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900}
The document is replaced!?
Attendez, tout le document «hostB» est remplacé par un autre nouveau document, ce n'est pas ce que nous voulons.
Pour mettre à jour une valeur particulière uniquement, utilise le modificateur de mise à jour$set
.
BasicDBObject newDocument = new BasicDBObject(); newDocument.append("$set", new BasicDBObject().append("clients", 110)); BasicDBObject searchQuery = new BasicDBObject().append("hosting", "hostB"); collection.update(searchQuery, newDocument);
Sortie
{ "_id" : { "$oid" : "id"} , "hosting" : "hostA" , "type" : "vps" , "clients" : 1000} { "_id" : { "$oid" : "id"} , "hosting" : "hostB" , "type" : "dedicated server" , "clients" : 110} { "_id" : { "$oid" : "id"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900}
Note
L'équipe MongoDB devrait créer une autre nouvelle API nomméeDBCollection.replace()
, de nombreux débutants sont piégés dans cette APIDBCollection.update()
et remplacent accidentellement le document entier. Encore une fois, pour mettre à jour une valeur particulière, utilisez$set
.
2. DBCollection.update() with $inc
Cet exemple montre l'utilisation du modificateur$inc
pour augmenter une valeur particulière. Recherchez le document où hébergement = «hostB», mettez à jour sa valeur «clients» en augmentant la valeur de 100 à 199, (100 + 99) = 199.
BasicDBObject newDocument = new BasicDBObject().append("$inc", new BasicDBObject().append("total clients", 99)); collection.update(new BasicDBObject().append("hosting", "hostB"), newDocument);
Sortie
{ "_id" : { "$oid" : "id"} , "hosting" : "hostA" , "type" : "vps" , "clients" : 1000} { "_id" : { "$oid" : "id"} , "hosting" : "hostB" , "type" : "dedicated server" , "clients" : 199} { "_id" : { "$oid" : "id"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900}
3. DBCollection.update() with multi
Cet exemple montre l'utilisation du paramètremulti
pour mettre à jour un ensemble de documents correspondants. Recherchez le document où type = «vps», mettez à jour la valeur «clients» de tous les documents correspondants à 888.
BasicDBObject updateQuery = new BasicDBObject(); updateQuery.append("$set", new BasicDBObject().append("clients", "888")); BasicDBObject searchQuery = new BasicDBObject(); searchQuery.append("type", "vps"); collection.updateMulti(searchQuery, updateQuery); //below statement set multi to true. //collection.update(searchQuery, updateQuery, false, true);
Sortie
{ "_id" : { "$oid" : "id"} , "hosting" : "hostA" , "clients" : "888" , "type" : "vps"} { "_id" : { "$oid" : "id"} , "hosting" : "hostB" , "type" : "dedicated server" , "clients" : 100} { "_id" : { "$oid" : "id"} , "hosting" : "hostC" , "clients" : "888" , "type" : "vps"}
Note
Si mise à jour sans le paramètremulti
défini sur true.
BasicDBObject updateQuery = new BasicDBObject(); updateQuery.append("$set", new BasicDBObject().append("clients", "888")); BasicDBObject searchQuery = new BasicDBObject(); searchQuery.append("type", "vps"); collection.update(searchQuery, updateQuery);
Vous remarquerez que seul le premier document correspondant est mis à jour.
{"_id":{ "$oid" : "x"} , "hosting" : "hostA" , "clients" : "888" , "type" : "vps"} {"_id":{ "$oid" : "x"} , "hosting" : "hostB" , "type" : "dedicated server" , "clients" : 100} {"_id":{ "$oid" : "x"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900}
Pour mettre à jour un ensemble de documents correspondants, vous devez définir «multi
» sur true.
4. Exemple complet
Exemple complet en combinant les extraits de code ci-dessus.
package com.example.core; import java.net.UnknownHostException; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.Mongo; import com.mongodb.MongoException; /** * Java MongoDB update document * * @author example * */ public class UpdateApp { public static void printAllDocuments(DBCollection collection) { DBCursor cursor = collection.find(); while (cursor.hasNext()) { System.out.println(cursor.next()); } } public static void removeAllDocuments(DBCollection collection) { collection.remove(new BasicDBObject()); } public static void insertDummyDocuments(DBCollection collection) { BasicDBObject document = new BasicDBObject(); document.put("hosting", "hostA"); document.put("type", "vps"); document.put("clients", 1000); BasicDBObject document2 = new BasicDBObject(); document2.put("hosting", "hostB"); document2.put("type", "dedicated server"); document2.put("clients", 100); BasicDBObject document3 = new BasicDBObject(); document3.put("hosting", "hostC"); document3.put("type", "vps"); document3.put("clients", 900); collection.insert(document); collection.insert(document2); collection.insert(document3); } public static void main(String[] args) { try { Mongo mongo = new Mongo("localhost", 27017); DB db = mongo.getDB("yourdb"); // get a single collection DBCollection collection = db.getCollection("dummyColl"); System.out.println("Testing 1...no $set"); insertDummyDocuments(collection); // find hosting = hostB, and update the clients to 110 BasicDBObject newDocument = new BasicDBObject(); newDocument.put("clients", 110); BasicDBObject searchQuery = new BasicDBObject().append("hosting", "hostB"); collection.update(searchQuery, newDocument); printAllDocuments(collection); removeAllDocuments(collection); System.out.println("\nTesting 1...with $set"); insertDummyDocuments(collection); BasicDBObject updateDocument = new BasicDBObject(); updateDocument.append("$set", new BasicDBObject().append("clients", 110)); BasicDBObject searchQuery2 = new BasicDBObject().append("hosting", "hostB"); collection.update(searchQuery2, updateDocument); printAllDocuments(collection); removeAllDocuments(collection); System.out.println("\nTesting 2... with $inc"); insertDummyDocuments(collection); // find hosting = hostB and increase it's "clients" value by 99 BasicDBObject newDocument2 = new BasicDBObject().append("$inc", new BasicDBObject().append("clients", 99)); collection.update(new BasicDBObject().append("hosting", "hostB"), newDocument2); printAllDocuments(collection); removeAllDocuments(collection); System.out.println("\nTesting 3... with $multi"); insertDummyDocuments(collection); // find type = vps , update all matched documents , clients value to 888 BasicDBObject updateQuery = new BasicDBObject(); updateQuery.append("$set", new BasicDBObject().append("clients", "888")); BasicDBObject searchQuery3 = new BasicDBObject(); searchQuery3.append("type", "vps"); collection.updateMulti(searchQuery3, updateQuery); // collection.update(searchQuery3, updateQuery, false, true); printAllDocuments(collection); removeAllDocuments(collection); System.out.println("Done"); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } } }
Sortie
Testing 1...no $set { "_id" : { "$oid" : "id"} , "hosting" : "hostA" , "type" : "vps" , "clients" : 1000} { "_id" : { "$oid" : "id"} , "clients" : 110} { "_id" : { "$oid" : "id"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900} Testing 1...with $set { "_id" : { "$oid" : "id"} , "hosting" : "hostA" , "type" : "vps" , "clients" : 1000} { "_id" : { "$oid" : "id"} , "hosting" : "hostB" , "type" : "dedicated server" , "clients" : 110} { "_id" : { "$oid" : "id"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900} Testing 2... with $inc { "_id" : { "$oid" : "id"} , "hosting" : "hostA" , "type" : "vps" , "clients" : 1000} { "_id" : { "$oid" : "id"} , "hosting" : "hostB" , "type" : "dedicated server" , "clients" : 199} { "_id" : { "$oid" : "id"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900} Testing 3... with $multi { "_id" : { "$oid" : "id"} , "hosting" : "hostB" , "type" : "dedicated server" , "clients" : 100} { "_id" : { "$oid" : "id"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900} { "_id" : { "$oid" : "id"} , "clients" : "888" , "hosting" : "hostA" , "type" : "vps"} Done