Smooth nested JSON structure in mongoDB

I have an object stored in MongoDB that looks like this:

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

I want to smooth this structure, so there is no attrib field, I only have the address and phone field along with name and _id .

So far this is what I have tried:

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

Can someone help me further?

+4
source share
2 answers

If you intend to change all the documents in the database, then neither the aggregation structure nor Map / Reduce will become their path. Instead, you write a script in your favorite language and iterate over all the documents in the collection to change them one by one.

+1
source

I tried:

 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' } } ); 

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

+6
source

Source: https://habr.com/ru/post/1494154/


All Articles