Anmol Jain
Anmol Jain

Reputation: 411

How to use the key of mongoDB collection as a key with some value in my query result?

Suppose this is my collection :

{
   {
      "productType":"bike",
      "productID":1,
      "lat":22.7,
      "long":77.4
   },
   {
      "productType":"car",
      "productID":5,
      "lat":25.7,
      "long":75.4
   },
   {
      "productType":"bike",
      "productID":2,
      "lat":26.7,
      "long":76.4
   }
}

I want to use the product type as key to my mongo query and grouping to get result like this :

{
   "bike":{
      "1":{
         "latitude":"22.7",
         "longitude":"77.4"
      },
      "2":{
         "latitude":"26.7",
         "longitude":"76.4"
      }
   },
   "car":{
      "5":{
         "latitude":"25.7",
         "longitude":"75.4"
      }
   }
}

I tried to use $replaceRoot but could not get the desired result.

Upvotes: 1

Views: 221

Answers (1)

Dheemanth Bhat
Dheemanth Bhat

Reputation: 4452

Try this query:

db.products.aggregate([
    {
        $group: {
            _id: "$productType",
            products: {
                $push: {
                    "k": { $toString: "$productID" },
                    "v": {
                        latitude: "$lat",
                        longitude: "$long"
                    }
                }
            }
        }
    },
    {
        $replaceWith: {
            array: [
                {
                    k: "$_id",
                    v: { $arrayToObject: "$products" }
                }
            ]
        }
    },
    {
        $replaceRoot: {
            newRoot: { $arrayToObject: "$array" }
        }
    }
]);

Output:

/* 1 */
{
    "bike" : {
        "1" : {
            "latitude" : 22.7,
            "longitude" : 77.4
        },
        "2" : {
            "latitude" : 26.7,
            "longitude" : 76.4
        }
    }
},

/* 2 */
{
    "car" : {
        "5" : {
            "latitude" : 25.7,
            "longitude" : 75.4
        }
    }
}

Upvotes: 1

Related Questions