sql >> Databasteknik >  >> NoSQL >> MongoDB

Hur man ökar befintligt värde i MongoDB

Enligt MongoDb 3.6:

db.collection.update(query, update, options)

Innebörden är att du kan rubba flera dokument med uppdatering.

Först bör du skapa en array från din karta som bara innehåller värdet.

const arrayOfValues = ['value_01', 'values_02'];

Då bör du använda alternativen upsert + multi på uppdateringsmetoden:

db.foo.update({value: { $in: arrayOfValues}}, {$inc: {count:1}}, { upsert: true, multi: true });

Testutgång:

> db.createCollection("test");
{ "ok" : 1 }
> db.test.insertMany([{value: "a"}, {value: "b"}, {value: "c"}];
... );
2017-12-31T12:12:18.040+0200 E QUERY    [thread1] SyntaxError: missing ) after argument list @(shell):1:61
> db.test.insertMany([{value: "a"}, {value: "b"}, {value: "c"}]);
{
    "acknowledged" : true,
    "insertedIds" : [
        ObjectId("5a48b8061b98cc5ac252e435"),
        ObjectId("5a48b8061b98cc5ac252e436"),
        ObjectId("5a48b8061b98cc5ac252e437")
    ]
}
> db.test.find();
{ "_id" : ObjectId("5a48b8061b98cc5ac252e435"), "value" : "a" }
{ "_id" : ObjectId("5a48b8061b98cc5ac252e436"), "value" : "b" }
{ "_id" : ObjectId("5a48b8061b98cc5ac252e437"), "value" : "c" }
> db.test.update({value: { $in: ["a", "b", "c"]}}, {$inc: {count:1}}, { upsert: true, multi: true });
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })
> db.test.find();
{ "_id" : ObjectId("5a48b8061b98cc5ac252e435"), "value" : "a", "count" : 1 }
{ "_id" : ObjectId("5a48b8061b98cc5ac252e436"), "value" : "b", "count" : 1 }
{ "_id" : ObjectId("5a48b8061b98cc5ac252e437"), "value" : "c", "count" : 1 }
> db.test.update({value: { $in: ["a", "b", "c"]}}, {$inc: {count:1}}, { upsert: true, multi: true });
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })
> db.test.find();
{ "_id" : ObjectId("5a48b8061b98cc5ac252e435"), "value" : "a", "count" : 2 }
{ "_id" : ObjectId("5a48b8061b98cc5ac252e436"), "value" : "b", "count" : 2 }
{ "_id" : ObjectId("5a48b8061b98cc5ac252e437"), "value" : "c", "count" : 2 }
> db.test.update({value: { $in: ["a", "b", "c"]}}, {$inc: {count:1}}, { upsert: true, multi: true });
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })

Hoppas det var till hjälp :)




  1. MongoDB, uppdatera samlingsfältet om det nya värdet inte är null

  2. Spring Boot redis Template autokabelkoppling misslyckades

  3. Enkel inloggningssida i nodejs med hjälp av express och pass med mongodb

  4. mongoDB Aggregation återställs tom