MongoDB索引-是否可以同时创建普通和复合?
是的,您可以使用sureIndex()。MongoDB为文档集合中任何字段上的索引提供完全支持。
让我们创建一个包含文档的集合-
> db.demo622.ensureIndex({_id:1,Name:1,Age:1});{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
> db.demo622.insertOne({_id:101,Name:"Chris",Age:21});
{ "acknowledged" : true, "insertedId" : 101 }
> db.demo622.insertOne({_id:102,Name:"Chris",Age:22});
{ "acknowledged" : true, "insertedId" : 102 }
> db.demo622.insertOne({_id:103,Name:"Bob",Age:21});
{ "acknowledged" : true, "insertedId" : 103 }
> db.demo622.insertOne({_id:104,Name:"Chris",Age:22});
{ "acknowledged" : true, "insertedId" : 104 }
> db.demo622.insertOne({_id:104,Name:"Chris",Age:22});
2020-04-18T12:21:18.085+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: test.demo622 index: _id_ dup key: { : 104.0 } :
WriteError({
"index" : 0,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: test.demo622 index: _id_ dup key: { : 104.0 }",
"op" : {
"_id" : 104,
"Name" : "Chris",
"Age" : 22
}
})
WriteError@src/mongo/shell/bulk_api.js:461:48
Bulk/mergeBatchResults@src/mongo/shell/bulk_api.js:841:49
Bulk/executeBatch@src/mongo/shell/bulk_api.js:906:13
Bulk/this.execute@src/mongo/shell/bulk_api.js:1150:21
DBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:252:9
@(shell):1:1
> db.demo622.insertOne({_id:105,Name:"Chris",Age:22});
{ "acknowledged" : true, "insertedId" : 105 }
在find()方法的帮助下显示集合中的所有文档-
> db.demo622.find();
这将产生以下输出-
{ "_id" : 101, "Name" : "Chris", "Age" : 21 }{ "_id" : 102, "Name" : "Chris", "Age" : 22 }
{ "_id" : 103, "Name" : "Bob", "Age" : 21 }
{ "_id" : 104, "Name" : "Chris", "Age" : 22 }
{ "_id" : 105, "Name" : "Chris", "Age" : 22 }
以上是 MongoDB索引-是否可以同时创建普通和复合? 的全部内容, 来源链接: utcz.com/z/331534.html