Test empty string in mongodb and pymongo

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

Here is my data structure.

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

\"lastname\" is sometimes present and

3条回答
  •  萌比男神i
    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" }
    

提交回复
热议问题