Syntax error How to force MongoDB to use the BasicCursor instead of an index?\\n

How to force MongoDB to use the BasicCursor instead of an index?\\n



To avoid using index, use hint() in MongoDB. Let us create a collection with documents −

> db.demo31.createIndex({"StudentFirstName":1});
{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}
> db.demo31.insertOne({"StudentFirstName":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e174f8fcfb11e5c34d898c1")
}
> db.demo31.insertOne({"StudentFirstName":"Jace"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e174f97cfb11e5c34d898c2")
}
> db.demo31.insertOne({"StudentFirstName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e174f9ccfb11e5c34d898c3")
}
> db.demo31.insertOne({"StudentFirstName":"James"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e174fa0cfb11e5c34d898c4")
}

Display all documents from a collection with the help of find() method −

> db.demo31.find();

This will produce the following output −

{ "_id" : ObjectId("5e174f8fcfb11e5c34d898c1"), "StudentFirstName" : "John" }
{ "_id" : ObjectId("5e174f97cfb11e5c34d898c2"), "StudentFirstName" : "Jace" }
{ "_id" : ObjectId("5e174f9ccfb11e5c34d898c3"), "StudentFirstName" : "Chris" }
{ "_id" : ObjectId("5e174fa0cfb11e5c34d898c4"), "StudentFirstName" : "James" }

Following is the query to force MongoDB to use BasicCursor instead of an index −

> db.demo31.find({"StudentFirstName": {$regex: '^Ja'}}).hint({ $natural: 1});

This will produce the following output −

{ "_id" : ObjectId("5e174f97cfb11e5c34d898c2"), "StudentFirstName" : "Jace" }
{ "_id" : ObjectId("5e174fa0cfb11e5c34d898c4"), "StudentFirstName" : "James" }
Updated on: 2020-04-02T12:39:38+05:30

189 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements