0

I would like to get find a key which is not there in MongoDB document. Please find the following document.

    {
"_id" : ObjectId("523b6e61fb408eea0eec2648"),
"userid" : "abby",
"score" : 82
}

I have a requirement that I need to query Mongo DB with a key which is not there in any document . say key =name. my db collection size is 10 GB. Now, I want to check the collection that the key = name is there or not ?

db.getCollection('score').find({"name":{$exists:true}})

the above query is taking more than 10 sec to find that weather the key name is there in the document or not. my question is that is there any way to get the response immediately if the specified key is not here in that document.

my question is different because when I check the link provided , I came to know that they are checking the existing key in a document. but in my case checking a key which is not there in any document.

Raju
  • 143
  • 5
  • Possible duplicate of [Improve querying fields exist in MongoDB](https://stackoverflow.com/questions/9009987/improve-querying-fields-exist-in-mongodb) – gil.fernandes Dec 06 '17 at 10:26

1 Answers1

0

I would simply create an index on that key:

db.score.createIndex({"name": 1})

This should speed up queries in general.

Edit 1:

My initial assumption is wrong: exists query are not speeded up by indices. More about this topic on: Improve querying fields exist in MongoDB

gil.fernandes
  • 12,978
  • 5
  • 63
  • 76
  • Thank you for reply .. I have tried adding index on name . And I have checked the number of documents examined then I came to know that again my query is taking the same time .. – Raju Dec 06 '17 at 10:16
  • @Raju: just saw this link here: https://stackoverflow.com/questions/9009987/improve-querying-fields-exist-in-mongodb . Indices do not work very well with exists query. The general suggestion is to change the schema, so that indices can be used efficiently. – gil.fernandes Dec 06 '17 at 10:24
  • Hi Gil, when I check the link which you have provided , I came to know that they are querying a key which is existing in the document. in my case the key is not exist in the document. instead of exist query , is there any way to get response quickly. – Raju Dec 06 '17 at 10:38
  • @Raju this type of query does a full table scan. That is why indices do not work and it is so slow. – gil.fernandes Dec 06 '17 at 11:04