having the following doc :
{
"_id" : ObjectId("xxx"),
"seller" : {
"phone" : {
"number" : "xx"
},
"nickname" : "xx"
},
"shipping" : {
"id" : xx
},
"id" : yyy,
"order_items" : {
"item" : {
"title" : "xxxyy"
},
"quantity" : 1
}}
and i need to convert to this output
{
"_id" : ObjectId("xxx"),
"seller.phone.number" : "xx",
"seller.nickname" : "xx",
"shipping.id" : "xx",
"id" : yyy,
"order_items.item.title" :"xxxyy",
"order_items.quantity" : 1
}
As you can see what i need to do is to flatten the document to a single level Im triying with the following code but mi output stills get nested
db.getCollection("collection").aggregate(
[
{
"$unwind" : {
"path" : "$order_items"
}
},
{
"$project" : {
"seller.phone.number" : 1.0,
"seller.nickname" : 1.0,
"shipping.id" : 1.0,
"id" : 1.0,
"order_items.item.title" : 1.0,
"order_items.quantity" : 1.0
}
}
],
{
"allowDiskUse" : false
}
);
Im starting to work with mongodb and studio3t any help would be appreciate regards
From the Mongo docs:
Otherwise, starting in MongoDB 3.6, the server permits storage of field names that contain dots (i.e. .) and dollar signs (i.e. $).
So while Mongo v3.6+ does allow for field names to contain dots they still provide the following warning:
Until support is added in the query language, the use of $ and . in field names is not recommended and is not supported by the official MongoDB drivers.
So studio3t has a custom driver they use as you can write queries in multiple languages but I believe they do just use the core drivers adjusted to your query language.
So what does this mean? this means the driver parses seller.phone.number
as a nested object.
What you can do is change the field names in the project stage:
{
"$project" : {
"seller_phone_number": "$seller.phone.number",
"seller_nickname": "$seller.nickname",
"id": 1,
"shipping_id": "$shipping.id",
"order_item_quantity": "$order_items.quantity",
"order_item_title": "$order_items.item.title",
}
}