mary
mary

Reputation: 57

How to get the rows extracted if few columns are blank or empty

I am new to this and would need some help in extracting the records/row only when few columns are blank. Below code is ignoring the blank records and getting me the ones with value. Can someone suggest here ?

mongo_docs = mongo.db.user.find({"$and":[{"Param1": {"$ne":None}}, {"Param1": {"$ne": ""}}]})

Sample data with expected output

Upvotes: 1

Views: 161

Answers (1)

veedata
veedata

Reputation: 1228

The query you are using contains ne which stands for not-equal. You can change that to eq (equals) and check if you get the desired results.

mongo_docs = mongo.db.user.find({"$or":[{"Param1": {"$eq":None}}, {"Param1": {"$eq": ""}}]})

A simplification of the above code will also be:

mongo_docs = mongo.db.user.find({"$or":[{"Param1": {"$eq":None, "$eq": ""}}]})

You can also use the exists query if that better satisfies your requirement.

From the comments: You are absolutely right, the command will work with multiple parameters.

mongo_docs = mongo.db.user.find({"$or":[{"Param1": {"$eq":None, "$eq": ""}}, {"Param2": {"$eq":None, "$eq": ""}},{"Param3": {"$eq":None, "$eq": ""}}]})

Additionally, if you want to do it over a larger range, you can consider using text indexes. These will allow you to search all the test fields at once, and the code for the same should look something like this:

mongo.db.user.createIndex({Param1: "text", Param2: "text", Param3: "text"})
mongo.db.user.find({$text: {$search: ""}})

The above works for text content only, and I have not come across any implementation for integer values yet but cannot see why the same should not work with some minor changes using other wildcards.


References:

  1. Search multiple fields for multiple values in MongoDB
  2. https://docs.mongodb.com/manual/text-search/
  3. https://docs.mongodb.com/manual/core/index-text/#std-label-text-index-compound
  4. https://docs.mongodb.com/manual/core/index-wildcard/

Upvotes: 0

Related Questions