1

I am not sure if this is possible with MongoDB. I can't find anything on it.

So I have a structure like:

{ "_id" : ObjectId("53cda1b0e03ab68fd4d8eb5e"), 
"radio_id" : "aoeuoae", 
"user_id" : "aoeuaoe", 
"email" : "", 
"songs" : 
    [ { "song_id" : ObjectId("53cda1b0e03ab68fd4d8eb5f"), 
        "added" : ISODate("2014-07-21T23:26:40.499Z"), 
        "liked" : 0, 
        "listened" : false }, 
      { "song_id" : ObjectId("53cda1b0e03ab68fd4d8eb60"), 
        "added" : ISODate("2014-07-21T23:26:40.499Z"), 
        "liked" : 0, 
        "listened" : false }]}

So the songs will keep adding on and song_id references another collection of songs.

What I want to do is make the song_id unique in the songs array. So if you tried to add another element like:

 "song_id" : ObjectId("53cda1b0e03ab68fd4d8eb60"), 
        "added" : ISODate("2014-07-21T23:26:40.499Z"), 
        "liked" : 0, 
        "listened" : false }

So I may push something like:

> db.users.update({'email':'jordan@howlett.io'}, {$push: {'songs': {'song_id': ObjectId("53cda1b0e03ab68fd4d8eb64")}}})

It would not work.

Is this possible? Thanks.

Jonovono
  • 1,979
  • 7
  • 30
  • 53
  • 1
    Possible duplicate: http://stackoverflow.com/questions/15921700/mongoose-unique-values-in-nested-array-of-objects – JohnnyHK Jul 22 '14 at 03:59

1 Answers1

3

Here is my best catch on how I had solved it in the past. With two calls.

found = db.col.find( {/*query*/}).count()
if found = 0:
    // update
    db.col.insert(storage_dict)
else:
    db.col.update({/*find the subdocument*/},{"$set":{'title : "Foo"}})

You can also "play" with the upsert parameter but I would not recommend for subdocuments like that.

Diolor
  • 13,181
  • 30
  • 111
  • 179
  • Thanks Diolor. That is what I did and I am still able to push to it it still allows it: > db.users.update({'email':'email'}, {$push: {'songs': {'song_id': ObjectId("53cda1b0e03ab68fd4d8eb64")}}}) – Jonovono Jul 22 '14 at 02:23
  • Cool, ya it looks like that's the way to do it! – Jonovono Jul 22 '14 at 16:38