Skip to content

Instantly share code, notes, and snippets.

@harlanji
Created August 23, 2011 07:41
Show Gist options
  • Save harlanji/1164586 to your computer and use it in GitHub Desktop.
Save harlanji/1164586 to your computer and use it in GitHub Desktop.
Creating a unique index on a nested array of objects.
// http://www.mongodb.org/display/DOCS/Multikeys
// Embedded object fields in an array
db.testnest.insert({"title" : "How the west was won",
"comments" : [{"text" : "great!" , "author" : "sam"},
{"text" : "ok" , "author" : "julie"}],
"_id" : ObjectId("497ce79f1ca9ca6d3efca325")});
// Tried both of these indexes
//db.testnest.ensureIndex({'comments.author': 1}, {unique: true});
db.testnest.ensureIndex({_id: 1, 'comments.author': 1}, {unique: true, dropDupes: true});
// I want this to fail
db.testnest.update({"_id" : ObjectId("497ce79f1ca9ca6d3efca325")}, {$push: {comments: {author: 'sam', text: 'wow'}}});
// this does what I expect, without an index:
db.testnest.update({"_id" : ObjectId("497ce79f1ca9ca6d3efca325"), 'comments.author': {$ne: 'julie'}}, {$push: {comments: {author: 'julie', text: 'I am not posted'}}});
// 'sam' is the author of two comments.
db.testnest.find();
/*
* Output:
{ "_id" : ObjectId("497ce79f1ca9ca6d3efca325"), "comments" : [
{
"text" : "great!",
"author" : "sam"
},
{
"text" : "ok",
"author" : "julie"
},
{
"author" : "sam",
"text" : "wow"
}
], "title" : "How the west was won" }
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment