如何在 MongoDB 未编制索引的字段上高效运行复杂查询?
创建一个索引以高效运行复杂查询。首先,让我们创建一个包含文档的集合 −
> db.demo400.insertOne({SubjectName:"Java Spring"}); { "acknowledged" : true, "insertedId" : ObjectId("5e610720fac4d418a0178572") } > db.demo400.insertOne({SubjectName:"Spring Hibernate"}); { "acknowledged" : true, "insertedId" : ObjectId("5e61072dfac4d418a0178573") } > db.demo400.insertOne({SubjectName:"Java Hibernate"}); { "acknowledged" : true, "insertedId" : ObjectId("5e610736fac4d418a0178574") } > db.demo400.createIndex({SubjectName:"text"}); { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
使用 find() 方法显示集合中的所有文档 −
> db.demo400.find();
这将产生以下输出 −
{ "_id" : ObjectId("5e610720fac4d418a0178572"), "SubjectName" : "Java Spring" } { "_id" : ObjectId("5e61072dfac4d418a0178573"), "SubjectName" : "Spring Hibernate" } { "_id" : ObjectId("5e610736fac4d418a0178574"), "SubjectName" : "Java Hibernate" }
以下是对未编制索引的字段执行复杂查询的查询 −
> db.demo400.find({ $text: { $search: "Spring" } } )
这将产生以下输出 −
{ "_id" : ObjectId("5e61072dfac4d418a0178573"), "SubjectName" : "Spring Hibernate" } { "_id" : ObjectId("5e610720fac4d418a0178572"), "SubjectName" : "Java Spring" }
广告