如何在 MongoDB 中为索引多个字段索引“or”?
要索引多个字段,请结合使用 ensureIndex()。通过 ensureIndex(),我们可以创建一个索引,甚至可以传递多个字段。我们来创建一个具有文档的集合−
> 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")
}借助 find() 方法显示集合中的所有文档−
> db.demo53.find();
这将产生以下输出−
{ "_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" }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP