“MongoDB -Update” Code-Antworten

Update in MongoDB

//insert:
db.members.insert({'user_id':1,'name':'nanhe'})
//update : 
db.members.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}})
Tiny Coders

Aktualisieren Sie die Tabelle in MongoDB

db.people.updateMany(
   { age: { $gt: 25 } },
   { $set: { status: "C" } }
)
--SQL 
UPDATE people
SET status = "C"
WHERE age > 25
Tiny Coders

MongoDB -Update

1	db.coll.update({"_id": 1}, {"year": 2016}) // WARNING! Replaces the entire document
2	db.coll.update({"_id": 1}, {$set: {"year": 2016, name: "Max"}})
3	db.coll.update({"_id": 1}, {$unset: {"year": 1}})
4	db.coll.update({"_id": 1}, {$rename: {"year": "date"} })
5	db.coll.update({"_id": 1}, {$inc: {"year": 5}})
6	db.coll.update({"_id": 1}, {$mul: {price: NumberDecimal("1.25"), qty: 2}})
7	db.coll.update({"_id": 1}, {$min: {"imdb": 5}})
8	db.coll.update({"_id": 1}, {$max: {"imdb": 8}})
9	db.coll.update({"_id": 1}, {$currentDate: {"lastModified": true}})
10	db.coll.update({"_id": 1}, {$currentDate: {"lastModified": {$type: "timestamp"}}})
11	
12	// Array
13	db.coll.update({"_id": 1}, {$push :{"array": 1}})
14	db.coll.update({"_id": 1}, {$pull :{"array": 1}})
15	db.coll.update({"_id": 1}, {$addToSet :{"array": 2}})
16	db.coll.update({"_id": 1}, {$pop: {"array": 1}})  // last element
17	db.coll.update({"_id": 1}, {$pop: {"array": -1}}) // first element
18	db.coll.update({"_id": 1}, {$pullAll: {"array" :[3, 4, 5]}})
19	db.coll.update({"_id": 1}, {$push: {scores: {$each: [90, 92, 85]}}})
20	db.coll.updateOne({"_id": 1, "grades": 80}, {$set: {"grades.$": 82}})
21	db.coll.updateMany({}, {$inc: {"grades.$[]": 10}})
22	db.coll.update({}, {$set: {"grades.$[element]": 100}}, {multi: true, arrayFilters: [{"element": {$gte: 100}}]})
23	
24	// Update many
25	db.coll.update({"year": 1999}, {$set: {"decade": "90's"}}, {"multi":true})
26	db.coll.updateMany({"year": 1999}, {$set: {"decade": "90's"}})
27	
28	// FindOneAndUpdate
29	db.coll.findOneAndUpdate({"name": "Max"}, {$inc: {"points": 5}}, {returnNewDocument: true})
30	
31	// Upsert
32	db.coll.update({"_id": 1}, {$set: {item: "apple"}, $setOnInsert: {defaultQty: 100}}, {upsert: true})
33	
34	// Replace
35	db.coll.replaceOne({"name": "Max"}, {"firstname": "Maxime", "surname": "Beugnet"})
36	
37	// Save
38	db.coll.save({"item": "book", "qty": 40})
39	
40	// Write concern
41	db.coll.update({}, {$set: {"x": 1}}, {"writeConcern": {"w": "majority", "wtimeout": 5000}})
Magnificent Monkey Adi

MongoDB -Update

db.collectionName.update({"aField":"vale1"},{$set:{"anotherField":"value2"}})

-search for documentations for more examples than search
-aField is used to find the documents
-anotherField is the field that will be updated
-You can also use the below:
-- updateOne
-- findOneAndUpdate
Karamolegkos

Ähnliche Antworten wie “MongoDB -Update”

Fragen ähnlich wie “MongoDB -Update”

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen