dark_shadow
dark_shadow

Reputation: 3573

How to perform an update on a nested object's array inside an array

I want to perform an update on a field which is present in a nested object in an array.

Consider this:

var PlatformPhotoAlbumSchema = new Schema({
  platformAlbumId: String,
  platformPhotoIds: [String]
}, { _id : false });

var SocialProfileSchema = new Schema({
  platformPhotoAlbums: [PlatformPhotoAlbumSchema]
});

Example:

{
platformPhotoAlbums: [
    {
    platformAlbumId: "a",
    platformPhotoIds: ["1","2"]
    },
    {
    platformAlbumId: "b",
    platformPhotoIds: ["3","4"]
    },
    {
    platformAlbumId: "c",
    platformPhotoIds: ["5","6"]
    }
]

}
  1. How can I update an existing object, for e.g., platformAlbumId with "c" with platformPhotoIds: ["5","6","7"]
  2. If there is no document with platformAlbumId with "c", then create a new object with platformAlbumId as "c" and platformPhotoIds: ["5","6","7"] and insert into platformPhotoAlbums.

I want to do this in one single mongodb query. Any idea how can this be done ?

Upvotes: 0

Views: 66

Answers (1)

wesww
wesww

Reputation: 2873

from the looks of what you're trying to accomplish, I think there is a simpler concept to think of for what your query actually will need to do

you want to push a new object into an array of objects that looks like

{
  platformAlbumId: "c",
  platformPhotoIds: ["5","6"]
}

and (before doing that) remove all preexisting items in the array that match a find for platformAlbumId: "c"

Edit:

actually better than that, you should be able to use findAndModify command with the query of your platformAlbumId values, update set with your new platformPhotoIds values, and upsert bool set to true http://docs.mongodb.org/manual/reference/command/findAndModify/

Upvotes: 1

Related Questions