Test empty string in mongodb and pymongo

前端 未结 3 1516
闹比i
闹比i 2020-12-15 03:26

Here is my data structure.

[{
\"name\": \"David\",
\"lastname\": \"\",
},
{
\"name\": \"Angela\"
}]

\"lastname\" is sometimes present and

相关标签:
3条回答
  • 2020-12-15 04:17

    Facing this problem I thought in another solution:

    db.collection.find({"lastname": {"$gte": " "}})
    

    With this I could get only the not empty strings, also ignoring null and not existent field, because any printable value (ASCII) has a greater value than space (32).

    https://en.wikipedia.org/wiki/ASCII

    0 讨论(0)
  • 2020-12-15 04:22
    db.collection.find({"lastname" : {"$exists" : true, "$ne" : ""}})
    

    In the mongo shell (id's omitted to save space)

    > db.collection.find()
      { "name" : "Angela" }
      { "name" : "David", "lastname" : "" }
      { "name" : "Kyle",  "lastname" : "Test" }
      { "name" : "John",  "lastname" : null }
    
    > db.collection.find({"lastname" : {"$exists" : true, "$ne" : ""}})
      { "name" : "Kyle", "lastname" : "Test" }
      { "name" : "John",  "lastname" : null }
    

    In case you also want to filter out matches against null values you need to adjust the criteria as follows (we can also get rid of $exists as "$ne": null takes care of this)

    > db.collection.find({$and:[{"lastname": {"$ne": null}}, {"lastname": {"$ne": ""}}]})
      { "name" : "Kyle", "lastname" : "Test" }
    
    0 讨论(0)
  • 2020-12-15 04:24

    You can use a regex query:

    db.test.find({ "lastname": /(.|\s)*\S(.|\s)*/ })

    This regex matches strings beginning or ending with 0 or N whitespaces (.|\s) and it have to be one or more non-whitespaces \S in the middle.

    0 讨论(0)
提交回复
热议问题