ThinkingInBits
ThinkingInBits

Reputation: 11422

MongoDB moving array of sub-documents to it's own collection

I'm looking to move an array of subdocuments into a collection of it's own keyed by the owner id. Currently, my collection is formed like this:

"_id": ObjectId("123"),
"username": "Bob Dole",
"logins": [{
  "_id": ObjectId("abc123"),
  "date": ISODate("2016")
}, {
  "_id": ObjectId("def456"),
  "date": ISODate("2016")
}]

I'm looking for the best way to write a script that would loop over each user, and move each item in the logins array to it's own "logins" collection, as follows:

{
    "_id": ObjectId("abc123"),
    "_ownerId": ObjectId("123"),
    "date": ISODate("2016")
}
{
    "_id": ObjectId("def567"),
    "_ownerId": ObjectId("123"),
    "date": ISODate("2016")
}

When the script ends, I'd like the login array to be removed entirely from all users.

Upvotes: 1

Views: 996

Answers (1)

profesor79
profesor79

Reputation: 9473

this query will create new collection using aggregation framework to see how it looks - just remove $out pipeline phase

db.thinking.aggregate([
{
    $unwind:"$logins"
},{
    $project:{
        _id:"$logins._id",
         _ownerId:"$_id",
        date:"$logins.date"
    }   
},
{ 
    $out: "newCollection" 
}
])

to delete array records - as suggested in comment:

db.thinking.update({},{ "$unset": { "logins": "" } },{ "multi": true })

Upvotes: 3

Related Questions