2016-10-24 31 views
0

私はmongoDBを使い慣れていないので、コレクションのオブジェクトから抽出するフィールドはほんのわずかです。次のようなレシピという名前のコレクションがあります。 -mongodbのオブジェクトからいくつかのフィールドを抽出しています

[ 
    { 
    "_id": "b44e864d-de8f-4110-b676-bbee13417b2e", 
    "title": "Fried Eggs", 
    "ingredients": [ 
     { 
     "name": "Eggs", 
     "amount": "10" 
     }, 
     { 
     "name": "Olive Oil", 
     "amount": "2 tbs" 
     } 
    ], 
    "steps": [ 
     "1. Heat the pan", 
     "2.Add Olive Oil", 
     "3. Add Eggs", 
     "4. Saute" 
    ], 
    "comments": [ 
     { 
     "_id": "8604e67c-2426-4742-bc91-25ee1c4064b5", 
     "poster": "Ron Swanson", 
     "comment": "Wrong instructions, Got stuck in Toaster" 
     }, 
     { 
     "_id": "040412bc-9046-49ca-9a65-19151b32cd91", 
     "poster": "Tom Haverford", 
     "comment": "What are Eggs?" 
     }, 
     { 
     "_id": "1034f082-b802-4382-be3e-ef50f07a530a", 
     "poster": "Andy Dwyer", 
     "comment": "What came firsst, Eggs or Chicken" 
     } 
    ] 
    }, 
    { 
    "_id": "da6f9798-6547-42f5-85ed-043efabeb196", 
    "title": "Boiled Eggs", 
    "ingredients": [ 
     { 
     "name": "Eggs", 
     "amount": "5" 
     }, 
     { 
     "name": "Water", 
     "amount": "3 Cups" 
     } 
    ], 
    "steps": [ 
     "1.Boil the Water", 
     "2.Add Eggs", 
     "3. Keepit for 5 mins", 
     "4. Let it Cool Down", 
     "5. Peel off the shell" 
    ], 
    "comments": [ 
     { 
     "_id": "cc569ebb-1307-499a-b9ee-7b24e557859f", 
     "poster": "Ron Swanson", 
     "comment": "Wrong instructions, Got stuck in Oven" 
     }, 
     { 
     "_id": "4f02756a-6e1b-4bda-a928-b3c5e03b55d8", 
     "poster": "Leslie Knope", 
     "comment": "What are Eggs?" 
     }, 
     { 
     "_id": "0f34a5cc-ebe3-41b5-8f0b-6d1a3c206e6b", 
     "poster": "Andy Dwyer", 
     "comment": "Can I remove the shell first and then boil?" 
     } 
    ] 
    }] 

特定のルートにアクセスしたときに両方のレシピのタイトルとIDだけを抽出したいとします。現在、私は両方のレシピのすべてのフィールドを返すこの関数を使用しています。

var recipesCollection = db.collection("recipes"); 
     exports.getAllRecipes = function() { 
      return recipesCollection.find({}).toArray(); 
     }; 

2つのレシピのタイトルとIDだけを抽出するために使用するクエリーはありますか?

答えて

1

私の理解によれば、あなたはmongoコレクションから特定のフィールドをフェッチしようとしています。プロジェクションを使うだけでこれを達成できます。詳細については

var recipesCollection = db.collection("recipes"); 
exports.getAllRecipes = function() { 
    return recipesCollection.find({}, {"title": 1}).toArray(); 
}; 

これに従ってください: https://docs.mongodb.com/v3.2/tutorial/project-fields-from-query-results/#return-the-specified-fields-and-the-id-field-only

+0

はどうもありがとうございました。 –

+0

質問がもう1つありますが、どのようにddo –

+0

あなたの質問を更新できますか? – mani

関連する問題