In my collection, I have a users
field as an array of the User collection.
So, it currently looks like this:
{ "name" : "Untitled", "users" : [ { "name" : "Ace Ventura", "datecreated" : "2012-10-05T23:55:56.940Z", "_id" : "740063fb-79c5-4f7f-96e1-907d6ffb1d16" } ], "datecreated" : "2012-10-05T23:55:56.954Z", "_id" : "e207eaea-89f7-48ae-8ba7-b6aa39db2358" }
I'd like to update it so that the array of User collection becomes just an array of the _id
property of the User collection. Like so:
{ "name" : "Untitled", "users" : ["740063fb-79c5-4f7f-96e1-907d6ffb1d16" ], "datecreated" : "2012-10-05T23:55:56.954Z", "_id" : "e207eaea-89f7-48ae-8ba7-b6aa39db2358" }
How would I accomplish this?
Thanks in advance.
Alright, I figured it out.
Initially, I was thinking of doing something like this:
db.lists.update(
{},
{
$set: {
users: <oldusers._id>
},
});
However, as it turns out, you cannot reference the current document's properties from within an update()
.
But, it turns out we can use forEach() :
db.lists.find().forEach(function (list) {
// Define length to ensure we have an array of users
var userLength = (list.users && list.users.length) || 0;
var (var i = 0; i < userLength; i++) {
// Ensure the current user object isn't null or undefined
if(list.users[i])
list.users[i] = list.users[i]._id
}
// Finally, save the list object back.
db.lists.save(list)
});
Thank, +gipset, for your answer here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.