Jonovono
Jonovono

Reputation: 2085

MongoDB: Unique on sub array of objects certain field

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':'[email protected]'}, {$push: {'songs': {'song_id': ObjectId("53cda1b0e03ab68fd4d8eb64")}}})

It would not work.

Is this possible? Thanks.

Upvotes: 1

Views: 303

Answers (1)

Diolor
Diolor

Reputation: 13450

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.

Upvotes: 3

Related Questions