its me
its me

Reputation: 542

Mongodb lookup and get output flat tree structure?

I have two collections points collection and users collection here i want to do aggregation based on userid.

here i am trying aggregation and everything is working fine but i need to modify result

db.points.aggregate([ 
     $match: {
      store: "001",
      date: {$lte: ISODate("2017-11-10T08:15:39.736Z"), $gte: ISODate("2017-11-10T08:15:39.736Z")}
    },

    {
    $lookup: {
      from: "users",
      localField: "userid",
      foreignField: "_id",
      as: "user"
    }
  },

   {

       $project: 

       {


       _id:0,
       "userdata.purchasedetails.purchaseid" : 1,
       "userdata.purchasedetails.data" : 1,
       usermobinumber: { "$arrayElemAt": [ "$user.mobinumber", 0 ] }



    }}  

Data stored like this

{
    "userpoint": "2",
    "date":ISODate("2017-11-10T08:15:39.736Z"),
    "store":"001",
    "userid":[
    objectID("5a7565ug8945rt67"),
    objectID("8a35553d3446rt78")
    ],
    "userdata":{
        "profile":[],
        "purchasedetails":
        [{
                "purchaseid":"dj04944",
                "data":"awe"

        }]
    }
}

getting result like this :

{
"usermobinumber":"9611",
"userdata":{
        "purchasedetails":
        [{
                "purchaseid":"dj04944",
                "data":"awe"

        }]
}

my expecting result:

I dont want tree structure output i need like this

{
 "usermobinumber":"9611",
 "purchaseid":"dj04944",
 "data":"awe"
 }

how can i do this help me out

Upvotes: 1

Views: 1658

Answers (2)

Thierry Barnier
Thierry Barnier

Reputation: 47

You can add an $unwind stage to flatten the result....

Upvotes: 0

Anirudh Bagri
Anirudh Bagri

Reputation: 2447

You can do something like this here,

db.points.aggregate([
    //Whatever you are doing here now (lookup and match)
    {
        $project:{
            "usermobinumber":"$usermobinumber",
            "purchaseid":"$userdata.purchasedetails.purchaseid"
        }
    }
])

This will give you:

{
    "usermobinumber" : "9611",
    "purchaseid" : [ 
        "dj04944"
  ]
}

EDIT:

db.points.aggregate([
        //Whatever you are doing here now (lookup and match)
        {
            {
             $project:{
                 "usermobinumber":"$usermobinumber",
                 "purchaseid":"$userdata.purchasedetails.purchaseid",
                 "data":"$userdata.purchasedetails.data"
               }
            }
        }
    ])

This will give you

{
 "usermobinumber":"9611",
 "purchaseid":["dj04944"],
 "data":["awe"]
 }

purchaseid and data are array because purchasedetails is an array.

Upvotes: 3

Related Questions