Skip to content

Instantly share code, notes, and snippets.

@jandot
Created February 23, 2010 16:09
Show Gist options
  • Save jandot/312343 to your computer and use it in GitHub Desktop.
Save jandot/312343 to your computer and use it in GitHub Desktop.
mongodb index and exists
// Suppose we have a collection "my_coll" with documents that look like this (we're talking about things that have positions on chromosomes):
// { _id: "1_123",
// chr: "1",
// pos: 123,
// accession_in_external_db: "an_id"
// },
// { _id: "1_456",
// chr: "1",
// pos: 456
// },
// { _id: "1_789",
// chr: "1",
// pos: 789,
// accession_in_external_db: "another_id"
// }
//
// Notice that the second document does _not_ have an accession_in_external_db.
//
// Get count of documents with an accession_in_external_db:
db.my_coll.find({'accession_in_external_db': {$exists: true}}).count()
// => 11604013
// But now create an index and try it again:
db.my_coll.ensureIndex({accession_in_external_db: 1})
db.my_coll.find({'accession_in_external_db': {$exists: true}}).count()
// => 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment