Created
August 23, 2011 07:41
-
-
Save harlanji/1164586 to your computer and use it in GitHub Desktop.
Creating a unique index on a nested array of objects.
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
// 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