MongoDb Remove last element from array if length is longer

I am using Mongodb, and the structure is as follows:

**{
    "_id" : ObjectId("5693af5d62f0d4b6af5124f1"),
    "uid" : 1,
    "terms" : [
        "sasasdsds",
        "test",
        "abcd"
    ]
}**

I want to remove the last element from the array if its length is greater than 10. Is it possible to do this in one request?

+4
source share
1 answer

Yes it is possible. What you use is a “dot notation” property to verify that the array contains at least 11 members, and then apply the update modifier $popto the array:

db.collection.update(
    { "terms.10": { "$exists": 1 } },
    { "$pop": { "terms": 1 } },
    { "multi": true }
)

, n-1 , , , , , $exists. $size, .

$pop .

, 10 , , $slice $push :

db.collection.update(
    { "terms.10": { "$exists": 1 } },
    { "$push": { "terms": { "$each": [], "$slice": 10 } } },
    { "multi": true }
)

$push, $each , ( ) , $slice . , ( n ), . "" "" n .

"multi" . , .

+5

Source: https://habr.com/ru/post/1623873/


All Articles