简体   繁体   中英

Pymongo: Select field into list without adding field name to list

I have a collection where one field is "ip" and I want to put all the IP values in a list like this:

["1.1.1.1", "2.2.2.2", "3.3.3.3"]

Here's what I've got so far:

result = db.ips.find({}, {"ip": 1, "_id":0}) # Cursor object
ip_list = list(result) #list
print ip_list

The ip_list is a list, but it looks JSON-y and contains not only the IPs, but also the field name:

[{u'ip': u'1.1.1.1'}, {u'ip': u'2.2.2.2'}, {u'ip': u'3.3.3.3'}]

How can I get the format with only the IP strings? I could loop over the whole list, of course, but I'm hoping there's a better way to go about it.

You should be able to use distinct :

print db.ips.distinct("ip")

Or if you need to filter first:

print db.ips.find(<foo>).distinct("ip")

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