MongoDBの配列内容の違いでソートするにはどうすればよいですか?
違いで並べ替えるには、MongoDBでaggregate()を使用します。ドキュメントを使用してコレクションを作成しましょう-
> db.demo155.insertOne({"Scores":[{"Value":45},{"Value":50}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e354584fdf09dd6d08539e3")
}
> db.demo155.insertOne({"Scores":[{"Value":60},{"Value":10}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e35458efdf09dd6d08539e4")
}
> db.demo155.insertOne({"Scores":[{"Value":100},{"Value":95}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e354599fdf09dd6d08539e5")
} find()メソッドを使用してコレクションからすべてのドキュメントを表示する-
> db.demo155.find();
これにより、次の出力が生成されます-
{ "_id" : ObjectId("5e354584fdf09dd6d08539e3"), "Scores" : [ { "Value" : 45 }, { "Value" : 50 } ] }
{ "_id" : ObjectId("5e35458efdf09dd6d08539e4"), "Scores" : [ { "Value" : 60 }, { "Value" : 10 } ] }
{ "_id" : ObjectId("5e354599fdf09dd6d08539e5"), "Scores" : [ { "Value" : 100 }, { "Value" : 95 } ] } 以下は、MongoDBを使用した配列の内容の違いで並べ替えるクエリです-
> db.demo155.aggregate([
... { "$match": { "Scores.1": { "$exists": true } } },
... { "$project": {
... "Scores": "$Scores",
... "sub": {
... "$let": {
... "vars": {
... "f": { "$arrayElemAt": [ "$Scores", -2 ] },
... "l": { "$arrayElemAt": [ "$Scores", -1 ] }
... },
... "in": { "$subtract": [ "$$l.Value", "$$f.Value" ] }
... }
... }
... }},
... { "$sort": { "sub": -1 } }
... ]) これにより、次の出力が生成されます-
{ "_id" : ObjectId("5e354584fdf09dd6d08539e3"), "Scores" : [ { "Value" : 45 }, { "Value" : 50 } ], "sub" : 5 }
{ "_id" : ObjectId("5e354599fdf09dd6d08539e5"), "Scores" : [ { "Value" : 100 }, { "Value" : 95 } ], "sub" : -5 }
{ "_id" : ObjectId("5e35458efdf09dd6d08539e4"), "Scores" : [ { "Value" : 60 }, { "Value" : 10 } ], "sub" : -50 } -
MongoDB配列の要素を削除するにはどうすればよいですか?
要素を削除するには、MongoDBで$ pullを更新して、使用します。 $ pull演算子は、既存の配列から、指定された条件に一致する1つまたは複数の値のすべてのインスタンスを削除します。 まず、ドキュメントを使用してコレクションを作成しましょう- db.demo541.insertOne({"software":{"services":["gmail","facebook","yahoo"]}});{ "acknowledged" : true
-
C#で配列クラスのSort()メソッドを使用するにはどうすればよいですか?
Sort()メソッドは、配列の各要素のIComparable実装を使用して、1次元配列全体の要素を並べ替えます。 アレイを設定します。 int[] list = { 22, 12, 65, 9}; Sort()メソッドを使用して配列を並べ替えます。 Array.Sort(list); 以下は、Sort()メソッドの操作方法を学ぶための例です。 例 using System; namespace Demo { class Program { static void Main(string[] args) {