How use sql "like" in PyMongo?

12,796

pymongo doesn't support regex literals, you have to use the '$regex' predicate:

 db.houses.find({"hid":{"$regex": u"9"}})
Share:
12,796

Related videos on Youtube

Ruslan Sharipov
Author by

Ruslan Sharipov

Updated on May 24, 2022

Comments

  • Ruslan Sharipov
    Ruslan Sharipov almost 2 years

    How use sql "like" in PyMongo?

    >>> db.houses.find().count()
    11616
    >>> db.houses.find({"hid":u"16999"}).count()
    1
    >>> db.houses.find({"hid":u"/9/"}).count()
    0
    

    The documentation says that sql "like" (SELECT * FROM users WHERE name LIKE "%Joe%") in MongoDB is db.users.find ({name:/Joe/}).

    If you specify a query directly to the cli-client interface mongodb, then everything works correctly, but does not work in pymongo.

    What is the problem?

    Thanks.

  • vogash
    vogash about 8 years
    what is the syntax if 9 represented as variable(search_word)? db.houses.find({"hid":{"$regex": usearch_word}}) .... ???
  • georg
    georg about 8 years
    @vogash: I guess, yes. Note that mongodb uses PCRE regexes, not python's.
  • vogash
    vogash about 8 years
    it says that variable usearch_word is not defined
  • vogash
    vogash about 8 years
    Any answer, can you send example of using parameter instead of hard coded 9
  • Geshan Ravindu
    Geshan Ravindu almost 3 years
    Worked for me in python 3.7. Thanks a lot.