複数のフィールドにインデックスを付けるために、MongoDBで「または」にインデックスを付けるにはどうすればよいですか?
複数のフィールドにインデックスを付けるには、組み合わせにensureIndex()を使用します。 sureIndex()を使用すると、インデックスを作成したり、複数のフィールドを渡すこともできます。ドキュメントを使用してコレクションを作成しましょう-
> 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" } -
MongoDB-ドキュメントのフィールドにアクセスするにはどうすればよいですか?
ドキュメントのフィールドにアクセスするには、find()を使用するだけです。ドキュメントを使用してコレクションを作成しましょう- > db.demo565.insertOne( ... { ... id:101, ... Name:"David", ... "CountryName":"US" ... } ... ); { "acknowledged" : true, "
-
MongoDB集計で複数のフィールドでカウント
複数のフィールドでカウントするには、MongoDBで$facetを使用します。 $ facetは、同じ入力ドキュメントのセットの単一ステージ内で複数の集約パイプラインを処理します。ドキュメントを使用してコレクションを作成しましょう- > db.demo721.insertOne( ... { ... ... "details1": { ... "id":101 ... ...