Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k 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 Reply

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}.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...