MongoDB positional upsert, update callbacks

495 views Asked by At

I have following structure in my collection:

{
    "_id" : {
        "id_1"    : "1",
        "id_2" : "1",
        "version" : "2.0"
    },
    "value" :
    [
        {
            "date"  :   ISODate("2014-10-01T00:00:00.000Z"),
            "val_1" : 0,
            "val_2" : 0,
            "count" : 0
        }
    ]
}

The main task is increment val_1, val_2 values by selecting it in following query:

db.runCommand({
    findAndModify: "coll",
    query  : {  "_id.id_1" : "1", "_id.id_2" : "1", "_id.version" : "2.0", value: { $elemMatch: { date: ISODate("2014-10-01T00:00:00.000Z") } } },
    update : { $inc:  {
        "value.$.val_1" : 1,
        "value.$.val_2" : 1,
        "value.$.count" : 1
    }
    }
});

It works fine if there is existing match, otherwise i got following exception:

"exception: The positional operator did not find the match needed from the query. Unexpanded update: value.$.val_1"

The first idea was to try find, if not exists - create, else update. After some research i have found following example ( from here NodeJS and MongoDB FindAndModify() need remove or update ):

collection.findAndModify(
    { "_id": "auto" },
    { "$inc": { "bill": 1 } },
    { "remove": true },
    function(err,doc) {
    // work here
    }
);

But the callbacks wont work in my MongoDB 2.6.3 version.

How i can achieve this described goal?

0

There are 0 answers