开发者

MongoDB : Update statement help, add a counter equal to length of an array in object?

This is the object:

{ "_id" : "c12345", 
  "arr" : [
        {
                "i" : 270099850,
                "a" : 772,

        },
        {
                "i" : 286855630,
                "a" : 622,

        }
] }

This is the statement that adds one more element to "arr":

db.testc.update({"_id" : "c12345"},{$pushAll:{"f":[{"i":123,"a":456456}]},   {"safe":false,"upsert" : true}}

THE MAIN REQUIREMENT IS : I want one statement like :

 db.testc.update({"_id" : "c12345"},{$pushAll:{"f":[{"i":123,"a":456456}]},
             $set:{"n":开发者_Go百科"this.f.lenth" }, {"safe":false,"upsert":true}) 

Which will add or modify a key "n" and put an integer as value which equals length of arr . I want to do it in same statement i.e. without doing a find .

The statement should ideally update it to final length of the "arr" ( or even initial would work by adding 1 to it)


You can't write something like this.f.length.

{ "$pushAll" : { "f" : [{ "i" : 123, "a" : 456456 }] }, "$set" : { "n" : 2 } }

You can use $inc to increment n (increament value should be equal pushed array length) on each update:

{ "$pushAll" : { "f" : [{ "i" : 123, "a" : 456456 }] }, "$inc" : { "n" : 1 } }

No need to use find.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜