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

MongoDBドキュメント内の配列アイテムを取得しますか?


MongoDBドキュメントの配列アイテムを取得するには、ドット(。)表記を使用します。ドキュメントを使用してコレクションを作成しましょう-

> db.demo29.insertOne({"StudentDetails":[{"StudentName":"Chris","StudentMarks":58},{"StudentName":"Bob","StudentMarks":69}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e15fcc08f2315c2efc48e6e")
}
>db.demo29.insertOne({"StudentDetails":[{"StudentName":"David","StudentMarks":97},{"StudentName":"Carol","StudentMarks":96}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e15fcd38f2315c2efc48e6f")
}

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

> db.demo29.find().pretty();

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

{
   "_id" : ObjectId("5e15fcc08f2315c2efc48e6e"),
   "StudentDetails" : [
      {
         "StudentName" : "Chris",
         "StudentMarks" : 58
      },
      {
         "StudentName" : "Bob",
         "StudentMarks" : 69
      }
   ]
}
{
   "_id" : ObjectId("5e15fcd38f2315c2efc48e6f"),
   "StudentDetails" : [
      {
         "StudentName" : "David",
         "StudentMarks" : 97
      },
      {
         "StudentName" : "Carol",
         "StudentMarks" : 96
      }
   ]
}

以下は、MongoDBドキュメント内の配列アイテムを取得するためのクエリです-

> db.demo29.find({"StudentDetails.StudentName":"David"});

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

{ "_id" : ObjectId("5e15fcd38f2315c2efc48e6f"), "StudentDetails" : [ { "StudentName" : "David", "StudentMarks" : 97 }, { "StudentName" : "Carol", "StudentMarks" : 96 } ] }

  1. ドキュメント内の配列内のオブジェクトを更新するためのMongoDB構文?

    これには、MongoDBでfindOneAndUpdate()を使用します。 findOneAndUpdate()メソッドは、フィルターと並べ替えの基準に基づいて1つのドキュメントを更新します。 ドキュメントを使用してコレクションを作成しましょう- > db.demo553.insertOne( ... { ...    id:101, ...    "Name":"John", ...    midExamDetails: ...    [ ...   &

  2. MongoDB Aggregateを使用して、ドキュメントと配列要素の平均を取得しますか?

    このために、$groupおよびaggregate()とともに$avgを使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo598.insertOne( ...    { ...       Information:'Student', ...       id:100, ...       details:[ ...          {Name:'Chris',Ma