Last active
September 5, 2018 20:50
-
-
Save egoarka/81bb030ec85059683bbf75d2caa8164f to your computer and use it in GitHub Desktop.
working on nested arrays in mongodb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
{ | |
name, | |
tags: [{ | |
name, | |
subtags: [{ | |
name | |
}] | |
}] | |
} | |
*/ | |
// create indexes for this structure | |
db.test.createIndex({ name: 1, 'tags.name': 1, 'tags.subtags.name': 1 }) | |
// push tags | |
db.test.update({ name: 10 }, { | |
$push: { | |
tags: { | |
$each: [{ name: 2 }, { name: 3 }, { name: 6 }] | |
} | |
} | |
}) | |
// push subtags placed in tag matched by name | |
db.test.update({ name: 10, 'tags.name': 14 }, { | |
$push: { | |
'tags.$.subtags': { | |
$each: [{ name: 3 }, { name: 4 }, { name: 5 }] | |
} | |
} | |
}) | |
// find value placed in subtags | |
db.test.find({ name: 10, 'tags.name': 20, 'tags.subtags.name': 30 }) | |
// update subtags' value (name) mathed by query | |
db.test.update( | |
{ name: 10 }, | |
{ $inc: { "tags.$[t].subtags.$[s].name": 2 } }, | |
{ arrayFilters: [ { "t.name": 20 } , { "s.name": 40 } ] } | |
) | |
// update tags' specific (!) value | |
// { 'tags.$': { name: 15 } } (rewrite whole object itself) | |
db.test.update({ name: 10, 'tags.name': 14 }, { | |
$set: { | |
'tags.$.name': 15 | |
} | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment