MongoDBの上位N行をクエリする方法は?
MongoDBの上位N行をクエリするには、集約フレームワークを使用できます。ドキュメントを使用してコレクションを作成しましょう
> db.topNRowsDemo.insertOne({"StudentName":"Larry","Score":78});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca26eee6304881c5ce84b91")
}
> db.topNRowsDemo.insertOne({"StudentName":"Chris","Score":45});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca26ef66304881c5ce84b92")
}
> db.topNRowsDemo.insertOne({"StudentName":"Mike","Score":65});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca26efe6304881c5ce84b93")
}
> db.topNRowsDemo.insertOne({"StudentName":"Adam","Score":55});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca26f066304881c5ce84b94")
}
> db.topNRowsDemo.insertOne({"StudentName":"John","Score":86});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca26f0f6304881c5ce84b95")
} 以下は、find()メソッドを使用してコレクションからすべてのドキュメントを表示するためのクエリです
> db.topNRowsDemo.find().pretty();
これにより、次の出力が生成されます
{
"_id" : ObjectId("5ca26eee6304881c5ce84b91"),
"StudentName" : "Larry",
"Score" : 78
}
{
"_id" : ObjectId("5ca26ef66304881c5ce84b92"),
"StudentName" : "Chris",
"Score" : 45
}
{
"_id" : ObjectId("5ca26efe6304881c5ce84b93"),
"StudentName" : "Mike",
"Score" : 65
}
{
"_id" : ObjectId("5ca26f066304881c5ce84b94"),
"StudentName" : "Adam",
"Score" : 55
}
{
"_id" : ObjectId("5ca26f0f6304881c5ce84b95"),
"StudentName" : "John",
"Score" : 86
} MongoDBの上位N行をクエリする方法は次のとおりです
> db.topNRowsDemo.aggregate([
... {$sort: {StudentName: 1}},
... {$limit: 5},
... {$match: {Score: {$gt: 65}}}
... ]).pretty(); これにより、次の出力が生成されます
{
"_id" : ObjectId("5ca26f0f6304881c5ce84b95"),
"StudentName" : "John",
"Score" : 86
}
{
"_id" : ObjectId("5ca26eee6304881c5ce84b91"),
"StudentName" : "Larry",
"Score" : 78
} -
MongoDBのサブドキュメントで検索クエリを実行するにはどうすればよいですか?
サブドキュメントの場合は、ドット表記を使用します。まず、ドキュメントを使用してコレクションを作成しましょう- > db.demo537.insertOne({"details":{"SubjectName":"MongoDB"}});{ "acknowledged" : true, "insertedId" : ObjectId("5e8c8a10ef4dcbee04fbbc05") } > db.demo537
-
「like」に似たMongoDBをクエリする方法は?
「like」と同様に実装するには、MongoDBで//と一緒にfind()を使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo686.insertOne({"FirstName":"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea55182a7e81adc6a0b395c") } > db.demo686.insertO