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

It would not work.

Is this possible? Thanks.

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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")}}})
Cool, ya it looks like that's the way to do it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.