MongoDB
 Computer >> コンピューター >  >> プログラミング >> MongoDB

MongoDBのサブドキュメントで並べ替え


サブドキュメントで並べ替えるには、MongoDBで$sortを使用します。ドキュメントを使用してコレクションを作成しましょう-

> db.demo245.insertOne(
...   {
...      "_id": 101,
...      "deatils": [
...         { "DueDate": new ISODate("2019-01-10"), "Value": 45},
...         {"DueDate": new ISODate("2019-11-10"), "Value": 34 }
...      ]
...   }
...);
{ "acknowledged" : true, "insertedId" : 101 }
> db.demo245.insertOne(
...   {
...      "_id": 102,
...      "details": [
...         { "DueDate": new ISODate("2019-12-11"), "Value": 29},
...         {"DueDate": new ISODate("2019-03-10"), "Value":  78}
...      ]
...   }
...);
{ "acknowledged" : true, "insertedId" : 102 }

find()メソッドを使用してコレクションからすべてのドキュメントを表示する-

> db.demo245.find();

これにより、次の出力が生成されます-

{
   "_id" : 101, "deatils" : [
      { "DueDate" : ISODate("2019-01-10T00:00:00Z"), "Value" : 45 },
      { "DueDate" : ISODate("2019-11-10T00:00:00Z"), "Value" : 34 }
   ]
}
{
   "_id" : 102, "details" : [
      { "DueDate" : ISODate("2019-12-11T00:00:00Z"), "Value" : 29 },
      { "DueDate" : ISODate("2019-03-10T00:00:00Z"), "Value" : 78 } \
   ] 
}

以下は、サブドキュメントで並べ替えるクエリです-

> db.demo245.aggregate([
...   { "$unwind": "$details" },
...   { "$sort": { "_id": 1, "details.Value": -1 } },
...   { "$group": {
...      "_id": "$_id",
...      "details": { "$push": "$details" }
...   }},
...   { "$sort": { "details.Value": -1 } }
...])

これにより、次の出力が生成されます-

{ "_id" : 102, "details" : [ { "DueDate" : ISODate("2019-03-10T00:00:00Z"), "Value" : 78 }, { "DueDate" : ISODate("2019-12-11T00:00:00Z"), "Value" : 29 } ] }

  1. MongoDBで自然に並べ替えるにはどうすればよいですか?

    $ naturalを使用して、MongoDBで自然を並べ替えます。ドキュメントを使用してコレクションを作成しましょう- > db.demo684.insertOne({Value:10}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ea530cea7e81adc6a0b3957") } > db.demo684.insertOne({Value:50}); {    "acknow

  2. MongoDBコレクションを配列値で並べ替えますか?

    MongoDBコレクションを配列値で並べ替えるには、$ sortとともにaggregate()を使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo577.insertOne( ...    { ... ...       "student": { ...          "details": [ ...             { ...   &