Is there a way to convert a nested document structure into an array? Below is an example:
Input
\"experience\" : {
\"0\" : {
See if this query works with your MongoDB version
For MongoDB version 3.2+:
db.doc.aggregate([
{$project:{experience:["$experience.0"]}}
])
MongoDB < 3.2:
db.doc.aggregate([
{$group: {_id:"$_id", experience:{$push:"$experience.0"}}}
])
It should transform your document into:
{
"_id" : ObjectId("56f1b046a65ea8a72c34839c"),
"experience" : [
{
"duration" : "3 months",
"end" : "August 2012",
"organization" : {
"0" : {
"name" : "Bank of China",
"profile_url" : "http://www.linkedin.com/company/13801"
}
},
"start" : "June 2012",
"title" : "Intern Analyst"
}
]
}
A better approach if you want to alter documents in collection permanently using aggregation framework.
Lets assume your collection name is doc
db.doc.aggregate([
{$group: {_id:"$_id", experience:{$push:"$experience.0"}}},
{$out: "doc"}
])
Query above will transform all of your documents in place.