Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten a nested JSON structure in mongoDB

Tags:

mongodb

I have an object stored in MongoDB which looks like:

{
_id: 123
name: "xyz"
    attrib: 
    {
       address: "123 xyz rd",
       phone: "123-456-7890"
    }
}

I want to flatted this structure, so that there is no attrib field, I just have address and phone field along with name and _id.

So far, this is what I've tried:

db.emp.aggregate(
    { 
    $project : {
            { addr : '$review.attrib.address' },
            { phn : '$review.votes.phone' },
        }
    }
);

Can anyone help me further?

like image 269
Vinay Pandey Avatar asked Jul 29 '13 22:07

Vinay Pandey


1 Answers

I tried it:

db.abc.insert({
  _id: 123,
  name: "xyz",
  attrib: {
     address: "123 xyz rd",
     phone: "123-456-7890"
  }
});
db.abc.aggregate(
{ 
  $project : {
    _id:1,
    name:1,
    addr : '$attrib.address',
    phn : '$attrib.phone' 
  }
}
);

More detail, you can see:use $project to rename fields http://docs.mongodb.org/manual/reference/aggregation/project/

like image 193
llx Avatar answered Sep 21 '22 03:09

llx