Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

mongoose - Mongodb: push element to nested array if the condition is met

I have the following collection:

{
    "_id": 11,
    "outerArray": [
        { "_id" : 21,
          "field": {
              "innerArray" : [
                  1,
                  2,
                  3
               ]
            }
        }, 
        { "_id" : 22,
          "field": {
              "innerArray" : [
                  2,
                  3
               ]
            }
        }, 
        { "_id" : 23,
          "field": {
              "innerArray" : [
                  2
               ]
            }
        }
    ]
}

I need to go through all documents in collection and push to innerArray new element 4, if innerArray already contains element 1 or element 3

I tried to do it this way, and few others, similar to this one, but it didn't work as expected, it only pushes to innerArray of first element of outerArray

db.collection.updateMany( 
    { "outerArray.field.innerArray": { $in: [ 1, 3 ] } },
    { $push: { "outerArray.$.field.innerArray": 4} }
)

How to make it push to all coresponding innerArrays?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Problem here is your missunderstanding a copule things.

When you do "outerArray.field.innerArray": { $in: [ 1, 3 ] } into your query, your are not getting only innerArray where has 1 or 3. You are gettings documents where exists these arrays.

So you are querying the entire document.

You have to use arrayFilter to update values when the filter is match.

So, If I've understood you correctly, the query you want is:

db.collection.update(
{}, //Empty object to find all documents
{
  $push: { "outerArray.$[elem].field.innerArray": 4 }
},
{
  "arrayFilters": [ { "elem.field.innerArray": { $in: [ 1, 3 ] } } ]
})

Example here

Note how the first object into update is empty. You have to put there the field to match the document (not the array, the document).

If you want to update only one document you have to fill first object (query object) with values you want, for example: {"_id": 11}.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...