问题
I want add new data my nested array
My document is:
{
\"username\": \"erkin\",
\"email\": \"erkin-07@hotmail.com\",
\"password\": \"b\",
\"playlists\": [
{
\"_id\": 58,
\"name\": \"asdsa\",
\"date\": \"09-01-15\",
\"musics\": [
{
\"name\": \"INNA - Cola Song (feat. J Balvin)\",
\"duration\": \"3.00\"
},
{
\"name\": \"blabla\",
\"duration\": \"3.00\"
}
]
}
]
}
I want add music in this playlist section:
{
\"username\": \"erkin\",
\"email\": \"erkin-07@hotmail.com\",
\"password\": \"b\",
\"playlists\": [
{
\"_id\": 58,
\"name\": \"asdsa\",
\"date\": \"09-01-15\",
\"musics\": [
{
\"name\": \"INNA - Cola Song (feat. J Balvin)\",
\"duration\": \"3.00\"
},
{
\"name\": \"blabla\",
\"duration\": \"3.00\"
},
{
\"name\": \"new\",
\"duration\": \"3.00\"
}
]
}
]
}
Here is what I tried:
$users->update(
array(
\'_id\' => new MongoId (Session::get(\'id\')),
\'playlists._id\' => $playlistId
),
array(
\'$push\' => array(\'playlists.musics\' => array(
\'name\' => \'newrecord\',
\'duration\' => \'3.00\'
))
)
);
回答1:
Probably something like this where ID is your ObjectId. The first {} are necessary to identify your document. It is not required to use an ObjectId as long as you have another unique identifier in your collection.
db.collection.update(
{ "_id": ID, "playlists._id": "58"},
{ "$push":
{"playlists.$.musics":
{
"name": "test name",
"duration": "4.00"
}
}
}
)
回答2:
This way it worked for me!
"playlists.$[].musics":
db.collection.update(
{ "_id": ID, "playlists._id": "58"},
{ "$push":
{"playlists.$[].musics":
{
"name": "test name",
"duration": "4.00"
}
}
}
)
https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/#position-nested-arrays-filtered
来源:https://stackoverflow.com/questions/27874469/mongodb-push-in-nested-array