Reputation: 759
I have a collection with "sensors" where each sensor looks like:
{
"_id" : ObjectId("5c3bfc66b5594738c8016d12"),
"parentDeviceID" : ObjectId("5c3b9aa0b559471f1088c5e1"),
"sn" : 2,
}
I would like to get a list of serial numbers ("sn") that belong to a particular parentDeviceID:
sensorList = list(self._dbC.sensorsCol.find({'parentDeviceID':parentDeviceID}, {'sn': 1, '_id':0}))
print(type(sensorList))
print(sensorList)
But I get list of dictionaries:
[{'sn': 1}, {'sn': 2}, {'sn': 3}]
I would like to get just:
[1,2,3]
Upvotes: 0
Views: 140
Reputation: 3760
Here's how you could do it via aggregation, server-side:
db.sensors.aggregate({"$group":{"_id":null,"sn":{"$push":"$sn"}}})
This will get you a single document like this:
{ "_id" : null, "sn" : [1, 2, 3] }
It should be trivial to extract the array from that.
The $group
over _id:null
means it constructs a single group for all the documents in the collection. The $push
aggregator constructs an array of all the sn
values in that group. Be aware that there is a document-size limit of 16 MB, so if your list of sensor ids could get larger than that, you might want a different, client-side solution.
Upvotes: 1