Created
May 31, 2012 17:38
-
-
Save Spoygg/2844964 to your computer and use it in GitHub Desktop.
Deleting embedded document from document, MongoDB shell with $pull
This file contains hidden or 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
> use test_database | |
> var pu = db.Profileusers | |
> pu.find({"blocks.title":""}).toArray() // find in Profileusers collection all profile users that have a block which title is empty | |
[ | |
{ | |
"_id" : ObjectId("4fc73221c0cd99aba79c7b74"), | |
"blocks" : [ | |
{ | |
"_id" : ObjectId("4fc78936376ab08618000000"), | |
"title" : "", // <-- here is the incriminating element, it's gonna fly muaaahaaaaaaa-ha-ha-ha (evil_grin) | |
"image" : "", | |
"description" : "", | |
"content" : "" | |
}, | |
{ | |
"_id" : ObjectId("4fc78988376ab0ec2d000000"), | |
"title" : "Efekat ♥", // <-- this one is safe for now | |
"image" : "", | |
"description" : "Some nicey nicey desc", | |
"content" : "Who needs a content for Fs' sake" | |
} | |
], | |
"password" : "password", // <-- totally safe, recommended ;) | |
"roles" : [ | |
"ROLE_ADMIN" | |
], | |
"username" : "SpoyggNew2" | |
} | |
] | |
> pu.update( {"blocks.title":""}, {$pull:{"blocks":{"title":""}}} ) // in Profileusers find all documents that have a block which title is empty | |
// and $pull all blocks that have an empty title. | |
// Some obvious notes: | |
// 1. You can select root document anyway you like | |
// 2. You can select embedded document anyway you like | |
// 3. What is important is this construct: | |
// db.<collection>.update( <clause for root>, {$pull:<clause for embed(s)>} ) | |
// 4. Since this is done with Mongo shell do not paste this comments!!! Anyway | |
// it will stick better if you write it on your own you lazy copy-paster! | |
> pu.find({}).toArray() | |
[ | |
{ | |
"_id" : ObjectId("4fc73221c0cd99aba79c7b74"), | |
"blocks" : [ // notice the absence of that ugly non-titled block :D | |
{ | |
"_id" : ObjectId("4fc78988376ab0ec2d000000"), | |
"title" : "Efekat ♥", | |
"image" : "", | |
"description" : "Some nicey nicey desc", | |
"content" : "Who needs a content for Fs' sake" | |
} | |
], | |
"password" : "password", // <-- once more, this is totally safe, use as much as possible :D | |
"roles" : [ | |
"ROLE_ADMIN" | |
], | |
"username" : "SpoyggNew2" | |
} | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment