how to query an element from a list in pymongo

2019-06-20 01:49发布

问题:

pymongo throws me an error when trying to query and element from tags

db.users.find({"pseudo":"alucaard"}).distinct("produit_up")
Out[1]: 
[{u'abus': 0,
  u'avctype': u'image/jpeg',
  u'date': u'2012-09-15',
  u'description': u'le fameux portable solide',
  u'id': u'alucaard134766932677',
  u'namep': u'nokia 3310',
  u'nombre': 1,
  u'orientation': u'portrait',
  u'photo': ObjectId('5053cd4e3a5f3a0990da8a61'),
  u'prix': 1000,
  u'tags': [u'solide', u'le', u'fameux', u'portable'],
  u'vendu': False}]

list(db.users.find({"solide":{"$in":{"document_up.tags"}}}))

Traceback (most recent call last):
 File "C:\Python27\lib\site-packages\IPython\core\interactiveshell.py", line 2746, in  run_code exec code_obj in self.user_global_ns, self.user_ns
File "<ipython-input-1-8dff98261d7a>", line 1, in <module>
list(db.users.find({"solide":{"$in":{"document_up.tags"}}}))
File "C:\Python27\lib\site-packages\pymongo\cursor.py", line 778, in next
if len(self.__data) or self._refresh():
File "C:\Python27\lib\site-packages\pymongo\cursor.py", line 729, in _refresh
self.__uuid_subtype))
InvalidDocument: Cannot encode object: set(['document_up.tags'])

NB: just a trick for the pymongo users, if your users have a limited size in text, just convert it using a set, the convert the set to a list: for example :

phrase = "hi you, how are you, am i using this"
  1. first step: remove comma or dots to avoid regular expression searchs.
  2. second, use phrase.split() to split words.
  3. add this to a set to avoid duplicate words.
  4. convert the set to a list
  5. it will be a good idea to make a dictionnary that containing some words that will be removed from the list, like "how", "you", "me", ... but it will make a lot of calculation.

hope this idea will help.

回答1:

Your query is wrong. Try something closer to:

list(db.users.find({"document_up.tags":{"$in":["solide"]}}))