Skip to content

Instantly share code, notes, and snippets.

@vipinrana
Last active November 21, 2020 13:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vipinrana/066e17eaba1d20ef127005db85e37dbd to your computer and use it in GitHub Desktop.
Save vipinrana/066e17eaba1d20ef127005db85e37dbd to your computer and use it in GitHub Desktop.
Sparse Index in mongodb
db.collection_name.insert([
{_id: 1, name: "John Doe", age: 25},
{_id: 2, name: "Foo Bar", age: 35},
{_id: 3, name: "Hello World"}
]);
// create sparse index
db.scores.createIndex( { age: 1 } , { sparse: true } );
// count the sparse Indexes Field will output 2
db.scores.find().hint("index_name").count();
// create without sparse index
db.scores.createIndex( { age: 1 } );
// count the non-sparse Indexes Field will output 3
db.scores.find().hint("index_name").count();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment