Home > Blockchain >  How i can update value in inner array using current value with criteria in MONGODB?
How i can update value in inner array using current value with criteria in MONGODB?

Time:05-19

I have a small mongo collection with inner arrays of strings.

{ 
    "_id" : ObjectId("62853dc84409dcc9213f8bca"), 
    "test" : [
        "aaaa", 
        "bbb", 
        "ccc"
    ]
}
{ 
    "_id" : ObjectId("62853dd74409dcc9213f8bcb"), 
    "test" : [
        "aaa", 
        "bbbb", 
        "ddddd"
    ]
}

How I can modify inner values in array with string length criteria, using current value? For example i want to concat * to all elems with length 3.

Result must be.

{ 
    "_id" : ObjectId("62853dc84409dcc9213f8bca"), 
    "test" : [
        "aaaa", 
        "bbb*", 
        "ccc*"
    ]
}
{ 
    "_id" : ObjectId("62853dd74409dcc9213f8bcb"), 
    "test" : [
        "aaa*", 
        "bbbb", 
        "ddddd"
    ]
}

I have some code, but it gives no result.

db.studs.updateMany(
    {}, 
    { $set: {"test.$[element]": { "$concat": ["element", " ", "*"]}}},
    { arrayFilters: [{"element": {"$strLenCP": {"$eq": 3}}}]})

CodePudding user response:

Query

  • you need $concat which is a aggregate operator
  • you can do it with pipeline update MongoDB >= 4.2
  • map and check size, if size=3 concat "*", else dont change the member of the array

*you tried to do it with update operators, but we cant mix the aggregate and the update operators, we either do pipeline update or normal update

Playmongo

db.studs.update({},
[{"$set": 
   {"test": 
     {"$map": 
       {"input": "$test",
        "in": 
         {"$cond": 
           [{"$eq": [{"$strLenCP": "$$this"}, 3]},
             {"$concat": ["$$this", "*"]}, "$$this"]}}}}}],
{"multi": true})
  • Related