MongoDBでコレクションのインデックスを表示するにはどうすればよいですか?
コレクションのインデックスを表示するには、getIndexes()を使用できます。構文は次のとおりです-
db.yourCollectionName.getIndexes();
概念を理解するために、ドキュメントを使用してコレクションを作成しましょう。ドキュメントを使用してコレクションを作成するためのクエリは次のとおりです-
> db.indexDemo.insertOne({"StudentName":"Larry","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8f7c4f2f684a30fbdfd599")
}
> db.indexDemo.insertOne({"StudentName":"Mike","StudentAge":24});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8f7c552f684a30fbdfd59a")
} find()メソッドを使用して、コレクションのすべてのドキュメントを表示します。クエリは次のとおりです-
> db.indexDemo.insertOne({"StudentName":"Carol","StudentAge":20}); 以下は出力です-
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8f7c5e2f684a30fbdfd59b")
}
> db.indexDemo.find().pretty();
{
"_id" : ObjectId("5c8f7c4f2f684a30fbdfd599"),
"StudentName" : "Larry",
"StudentAge" : 21
}
{
"_id" : ObjectId("5c8f7c552f684a30fbdfd59a"),
"StudentName" : "Mike",
"StudentAge" : 24
}
{
"_id" : ObjectId("5c8f7c5e2f684a30fbdfd59b"),
"StudentName" : "Carol",
"StudentAge" : 20
} インデックスを作成するためのクエリは次のとおりです-
> db.indexDemo.createIndex({"StudentName":-1,"StudentAge":-1}); 出力は次のとおりです。
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 2,
"numIndexesAfter" : 3,
"ok" : 1
} コレクションのインデックスを表示するためのクエリは次のとおりです。コレクション名は「indexDemo」-
です。> db.indexDemo.getIndexes();
以下は出力です-
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "test.indexDemo"
},
{
"v" : 2,
"key" : {
"StudentName" : -1
},
"name" : "StudentName_-1",
"ns" : "test.indexDemo"
},
{
"v" : 2,
"key" : {
"StudentName" : -1,
"StudentAge" : -1
},
"name" : "StudentName_-1_StudentAge_-1",
"ns" : "test.indexDemo"
}
] -
MongoDBコレクション内のすべてのドキュメントに新しいフィールドを追加する方法
新しいフィールドを追加するには、MongoDBで$addFieldsを使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo712.insertOne({"Name":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea85f675d33e20ed1097b82") } > db.demo712.insertOne({"
-
ネストされたMongoDBドキュメントのキーのみを表示するにはどうすればよいですか?
ドキュメントを使用してコレクションを作成しましょう- > db.demo740.insertOne({ ... "details": ... [ ... { ... Name:"Chris", ... Age:21, ... CountryName:&qu