Suppose we have collection of documents having array and we want to update document having array on the basis of some condition.
Table of Contents
Insert document in movies collection
db.movies.insertMany([ { title: "Phone Bhoot", actors: [ { age: 30, sex: "f", name: "n" }, { age: 20, sex: "f", name: "c" }, { age: 35, sex: "m", name: "s" }, { age: 40, sex: "m", name: "a" }, ], }, { title: "Sita Raman", actors: [ { age: 30, sex: "m", name: "se" }, { age: 20, sex: "f", name: "cn" genre:['action', 'romance', 'thrill', 'suspence]}, { age: 25, sex: "f", name: "sn" }, { age: 30, sex: "m", name: "an" }, ], }, { title: "Bharamsastra", actors: [ { age: 50, sex: "m", name: "ser" genre:['family', 'thrill']}, { age: 40, sex: "f", name: "cnr" }, { age: 25, sex: "f", name: "snr" }, { age: 30, sex: "m", name: "anr" , genre:['action', 'romance', 'thrill']}, ], }, ]);
The $[<identifier>]
operator facilitates updates to arrays that contain embedded documents. To access the fields in the embedded documents, use the dot notation with the $[<identifier>]
.
db.collection.updateMany(
{ <query selector> },
{ <update operator>: { "array.$[<identifier>].field" : value } },
{ arrayFilters: [ { <identifier>: <condition> } } ] }
)
Example 1: Increment age by 5 where tilte “Phone Bhoot” and age less than 30
db.movies.updateMany( { title: "Phone Bhoot" }, { $inc: { "actors.$[elem].age": 5 } }, { arrayFilters: [{ "elem.age": { $lt: 30 } }] } );
Example 2: set “senior” to “yes”, those age greater than 50
db.movies.updateMany( {}, { $set: { "actors.$[elem].senior": "yes" } }, { arrayFilters: [{ "elem.age": { $gt: 40 } }] } );
Example 3: set “diva” to “yes”, those age greater than equal 20 and less than equal to 30 and sex is f
db.movies.updateMany( {}, { $set: { "actors.$[elem].diva": "yes" } }, { arrayFilters: [{ "elem.age": { $gt: 18, $lte: 30 }, "elem.sex": "f" }] } );
Example 4: add “action” to genre whose age greater than equal 20 and less than equal to 30 and sex is m
db.movies.updateMany( {}, { $push: { "actors.$[elem].genre": "action" } }, { arrayFilters: [{ "elem.age": { $gte: 20, $lte: 30 }, "elem.sex": "m" }, ] } );
How it works ?
The filtered positional operator $[<identifier>]
identifies the array elements that match the arrayFilters
conditions for an update operation, Used in conjunction with the arrayFilters
option, the $[<identifier>]
operator has the following form:
{ <update operator>: { "<array>.$[<identifier>]" : value } },
{ arrayFilters: [ { <identifier>: <condition> } ] }
The
<identifier>
must begin with a lowercase letter and contain only alphanumeric characters.
Few other posts from Mongo DB
Source : MongoDB Doc