Gokulnath Thangavel
Gokulnath Thangavel

Reputation: 45

mongoDB group combination of distinct values and return array

My database is in MongoDB version 4.4 and I am using pymongo to fetch data. Suppose I have a MongoDB collection as shown below:

{
    "_id":1,
    "device":{"deviceId":'A1',"deviceName":'Some_device'},
    "location":{"latitude":12.3456,"longitude":-78.9}
}
{
    "_id":2,
    "device":{"deviceId":'A2',"deviceName":'Some_other_device'},
    "location":{"latitude":12.3456,"longitude":-78.9}
}
{
    "_id":3,
    "device":{"deviceId":'A1',"deviceName":'Some_device'},
    "location":{"latitude":11.1111,"longitude":-55.5555}
}
{
    "_id":4,
    "device":{"deviceId":'B1',"deviceName":'New_device'},
    "location":{"latitude":12.3456,"longitude":-55.5555}
}

I need for each unique combination of latitude and longitude, array of corresponding assets as shown below:

{
    "location":{"latitude":12.3456,"longitude":-78.9},
    {"device": "deviceId":['A1','A2'], "deviceName":['Some_device','Some_other_device']}
}
{
    "location":{"latitude":11.1111,"longitude":-55.5555},
    {"device": "deviceId":['A1'], "deviceName":['Some_device']}
}
{
    "location":{"latitude":12.3456,"longitude":-55.5555},
    {"device": "deviceId":['B1'], "deviceName":['New_device']}
}

I tried fetching all data at once and do the operation. But the collection is too large to respond. Is there anyway I can get the results with query operations?

Upvotes: 0

Views: 27

Answers (1)

Rajdeep D
Rajdeep D

Reputation: 3920

You can achieve this with aggregation

Working playground here

db.collection.aggregate([
  {
    "$group": {
      "_id": {
        latitude: "$location.latitude",
        longitude: "$location.longitude"
      },
      "deviceId": {
        "$addToSet": "$device.deviceId"
      },
      "deviceName": {
        "$addToSet": "$device.deviceName"
      }
    }
  },
  {
    "$project": {
      _id: 0,
      location: {
        latitude: "$_id.latitude",
        longitude: "$_id.longitude"
      },
      device: {
        deviceId: "$deviceId",
        deviceName: "$deviceName"
      }
    }
  }
])

Upvotes: 1

Related Questions