サブドキュメントの一致でソートするMongoDB?
サブドキュメントの一致で並べ替えるには、集約フレームワークを使用できます。まず、ドキュメントを使用してコレクションを作成しましょう-
> db.sortBySubDocumentsDemo.insertOne(
{
"StudentName": "Chris",
"StudentDetails": [
{
"Age":21,
"StudentScore":91
},
{
"Age":22,
"StudentScore":99
},
{
"Age":21,
"StudentScore":93
}
]
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd57e297924bb85b3f48942")
}
> db.sortBySubDocumentsDemo.insertOne(
{
"StudentName": "Robert",
"StudentDetails": [
{
"Age":24,
"StudentScore":78
},
{
"Age":21,
"StudentScore":86
},
{
"Age":23,
"StudentScore":45
}
]
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd57e4c7924bb85b3f48943")
} 以下は、find()メソッドを使用してコレクションからすべてのドキュメントを表示するためのクエリです-
> db.sortBySubDocumentsDemo.find().pretty();
これにより、次の出力が生成されます-
{
"_id" : ObjectId("5cd57e297924bb85b3f48942"),
"StudentName" : "Chris",
"StudentDetails" : [
{
"Age" : 21,
"StudentScore" : 91
},
{
"Age" : 22,
"StudentScore" : 99
},
{
"Age" : 21,
"StudentScore" : 93
}
]
}
{
"_id" : ObjectId("5cd57e4c7924bb85b3f48943"),
"StudentName" : "Robert",
"StudentDetails" : [
{
"Age" : 24,
"StudentScore" : 78
},
{
"Age" : 21,
"StudentScore" : 86
},
{
"Age" : 23,
"StudentScore" : 45
}
]
} 以下は、サブドキュメントの一致で並べ替えるクエリです。ここでは、StudentScoreで並べ替えています-
> db.sortBySubDocumentsDemo.aggregate([
{$match: { 'StudentDetails.Age': 21 }},
{$unwind: '$StudentDetails'},
{$match: {'StudentDetails.Age': 21}},
{$project: {_id: 0, "StudentName": 1, 'StudentDetails.StudentScore': 1}},
{$sort: { 'StudentDetails.StudentScore': 1 }},
{$limit: 5}
]); これにより、次の出力が生成されます-
{ "StudentName" : "Robert", "StudentDetails" : { "StudentScore" : 86 } }
{ "StudentName" : "Chris", "StudentDetails" : { "StudentScore" : 91 } }
{ "StudentName" : "Chris", "StudentDetails" : { "StudentScore" : 93 } } -
_idがサブドキュメントの一部として配列にあるドキュメントを照合するMongoDBクエリ?
ドキュメントを使用してコレクションを作成しましょう- > db.demo568.insertOne({ _id: 101, details: [ {id : 101 }, { id:103 } ] }); { "acknowledged" : true, "insertedId" : 101 } find()メソッドを使用してコレクションからすべてのドキュメントを表示する- > db.demo568.find(); これにより、次の出力が生成されます- { "_id" : 101, "details"
-
MongoDBコレクションを配列値で並べ替えますか?
MongoDBコレクションを配列値で並べ替えるには、$ sortとともにaggregate()を使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo577.insertOne( ... { ... ... "student": { ... "details": [ ... { ... &