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
Create index in a MongoDB collection?
To create index, use createIndex() in MongoDB. Let us create a collection with documents −
> db.demo702.createIndex({"details.id":1});
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
> db.demo702.insertOne({
... "details" : [
... {
... id:101,
... studentInfo:{
... "StudentName" : "Chris",
... "StudentAge" : 23,
... }
... },
... {
...
... id: 102,
... studentInfo:{
... "StudentName" : "Robert",
... "StudentAge" : 20,
... }
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea6ea3b551299a9f98c93b3")
}
Display all documents from a collection with the help of find() method −
> db.demo702.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5ea6ea3b551299a9f98c93b3"),
"details" : [
{
"id" : 101,
"studentInfo" : {
"StudentName" : "Chris",
"StudentAge" : 23
}
},
{
"id" : 102,
"studentInfo" : {
"StudentName" : "Robert",
"StudentAge" : 20
}
}
]
}Advertisements