Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do I index “or” in MongoDB for indexing multiple fields?
To index multiple fields, use ensureIndex() for a combination. With ensureIndex(), we can create an index and even pass multiple fields. Let us create a collection with documents −
> db.demo53.ensureIndex({"StudentFirstName":1,"StudentAge":1});
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
> db.demo53.ensureIndex({"StudentFirstName":1,"StudentCountryName":1});
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 2,
"numIndexesAfter" : 3,
"ok" : 1
}
>db.demo53.insertOne({"StudentFirstName":"Chris","StudentAge":21,"StudentCountryName":"US"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e271431cfb11e5c34d89911")
}
>db.demo53.insertOne({"StudentFirstName":"David","StudentAge":23,"StudentCountryName":"UK"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e27143ccfb11e5c34d89912")
}
>db.demo53.insertOne({"StudentFirstName":"Mike","StudentAge":24,"StudentCountryName":"AUS"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e27144bcfb11e5c34d89913")
}
Display all documents from a collection with the help of find() method −
> db.demo53.find();
This will produce the following output −
{ "_id" : ObjectId("5e271431cfb11e5c34d89911"), "StudentFirstName" : "Chris", "StudentAge" : 21, "StudentCountryName" : "US" }
{ "_id" : ObjectId("5e27143ccfb11e5c34d89912"), "StudentFirstName" : "David", "StudentAge" : 23, "StudentCountryName" : "UK" }
{ "_id" : ObjectId("5e27144bcfb11e5c34d89913"), "StudentFirstName" : "Mike", "StudentAge" : 24, "StudentCountryName" : "AUS" }Advertisements