Aakash Dusane
Aakash Dusane

Reputation: 398

How would I find documents based on whether a field exists AND another that doesn't, in MongoDB?

I have a bunch of documents that consists of fields "Data" and "Text". Some docs have either one, while some have neither of these. How would I query through pyMongo to get documents that HAVE the field "Data" and DO NOT HAVE the field "Text"?

I've tried the below queries but mongo doesn't return any files.

METHOD 1:

files = collection.find({"Data": {"$exists": "true"}, {"Text": {"$exists": "false"}})

for file in files:
    print(file)

METHOD 2:

files = collection.find({"$and": [{"Data": {"$exists": "true"}}, {"Text": {"$exists": "false"}}]})

for file in files:
    print(file)

NOTE: I'm currently trying the query on a database where no collections have the "Text" field (yet), but the query should still work w.r.t the logic. It being:

Return docs with "Data" AND not having "Text"

Upvotes: 1

Views: 1101

Answers (3)

Anushka Ahir
Anushka Ahir

Reputation: 146

You can refer this link : https://docs.mongodb.com/manual/tutorial/query-for-null-fields/

Try this

  collection.find({"Data": {"$exists": "true"}, {"Text": null })

query matches documents that either contain the Text field whose value is null or that do not contain the Text field.

If you could not resolve this then please post your data store in collections for reference and your schema structure.this will help us if you have problem with it.

Upvotes: 1

Aakash Dusane
Aakash Dusane

Reputation: 398

I tried using None instead of False as Anushka pointed out and it worked.

files = coll.find({"Data": {"$exists": "true"}, "Text": None})

If anyone knows why my initial attempt as stated below did not work, please comment on this answer. Thanks.

files = collection.find({"Data": {"$exists": "true"}, {"Text": {"$exists": "false"}})

Upvotes: 2

Rajat Rastogi
Rajat Rastogi

Reputation: 17

in using $exists:true any type of index usage goes out of equation. You can modify the query as files = collection.find({"Data":{$ne:null}, Text:null})

Upvotes: -1

Related Questions