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

Mongodbの配列内のドキュメントから特定のフィールドを投影する方法は?


配列内のドキュメントから特定のフィールドを投影するには、位置($)演算子を使用できます。

まず、ドキュメントを使用してコレクションを作成しましょう

> db.projectSpecificFieldDemo.insertOne(
   ... {
      ... "UniqueId": 101,
      ... "StudentDetails" : [{"StudentName" : "Chris", "StudentCountryName ": "US"},
         ... {"StudentName" : "Robert", "StudentCountryName" : "UK"},
      ... ]
      ... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca27aeb6304881c5ce84ba2")
}
> db.projectSpecificFieldDemo.insertOne( { "UniqueId": 102, "StudentDetails" :
   [{"StudentName" : "Robert", "StudentCountryName ": "UK"}, {"StudentName" : "David",
   "StudentCountryName" : "AUS"}, ] } );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca27b106304881c5ce84ba3")
}

以下は、find()メソッドを使用してコレクションからすべてのドキュメントを表示するためのクエリです

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

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

{
   "_id" : ObjectId("5ca27aeb6304881c5ce84ba2"),
   "UniqueId" : 101,
   "StudentDetails" : [
      {
         "StudentName" : "Chris",
         "StudentCountryName " : "US"
      },
      {
         "StudentName" : "Robert",
         "StudentCountryName" : "UK"
      }
   ]
}
{
   "_id" : ObjectId("5ca27b106304881c5ce84ba3"),
   "UniqueId" : 102,
   "StudentDetails" : [
      {
         "StudentName" : "Robert",
         "StudentCountryName " : "UK"
      },
      {
         "StudentName" : "David",
         "StudentCountryName" : "AUS"
      }
   ]
}

以下は、配列内のドキュメントから特定のフィールドを投影するためのクエリです

> var myDocument = { UniqueId : 101, 'StudentDetails.StudentName' : 'Chris' };
> var myProjection= {'StudentDetails.$': 1 };
> db.projectSpecificFieldDemo.find(myDocument , myProjection).pretty();

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

{
   "_id" : ObjectId("5ca27aeb6304881c5ce84ba2"),
   "StudentDetails" : [
      {
         "StudentName" : "Chris",
         "StudentCountryName " : "US"
      }
   ]
}

  1. MongoDB-ドキュメントのフィールドにアクセスするにはどうすればよいですか?

    ドキュメントのフィールドにアクセスするには、find()を使用するだけです。ドキュメントを使用してコレクションを作成しましょう- > db.demo565.insertOne( ... { ...    id:101, ...    Name:"David", ...    "CountryName":"US" ... } ... ); {    "acknowledged" : true,    "

  2. MongoDBドキュメントから特定の値をフィルタリングする

    特定の値をフィルタリングするには、MongoDBで$filterを使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo751.insertOne( ...    { ...       _id: 101, ...       details: [ ...          { Name: "Robert", id:110,Age:21}, ...         &nb