简体   繁体   中英

pymongo Query to flat list?

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]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM