0

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?

1 Answer 1

1

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"
      }
    }
  }
])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.