How to increment existing value in MongoDB

前端 未结 1 1079
孤街浪徒
孤街浪徒 2021-01-19 06:53

I am using Stitch platform by MongoDB. I want to store a value and a count associated with that value in the database. Now the value m

1条回答
  •  星月不相逢
    2021-01-19 07:52

    According to MongoDb 3.6:

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

    Modifies an existing document or documents in a collection. The method can modify specific fields of an existing document or documents or replace an existing document entirely, depending on the update parameter.

    The meaning is that you can upsert multiple documents using update.

    First you should create array from your map that contains only the value.

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

    Then you should use the upsert + multi options on the update method:

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

    Test output:

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

    Hope it was helpful :)

    0 讨论(0)
提交回复
热议问题