Skip to content

Instantly share code, notes, and snippets.

@egoarka
Last active September 5, 2018 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save egoarka/81bb030ec85059683bbf75d2caa8164f to your computer and use it in GitHub Desktop.
Save egoarka/81bb030ec85059683bbf75d2caa8164f to your computer and use it in GitHub Desktop.
working on nested arrays in mongodb
/*
{
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