2017-08-31 77 views
0

我有這個測驗文件:如何發佈隱藏了某些字段的數組中的某些元素?

{ 
    _id: 001, 
    quiz: "cartoon familes", 
    questions:[ 
    { 
     _id: 100, 
     question: "who is the eldest ?", 
     order: 1, 
     answers: [ 
        { _id: 101, answer: "Bart Simpson", points: 100 }, 
        { _id: 102, answer: "Lisa Simpson", points: 0 }, 
        { _id: 103, answer: "Maggie Simpson", points: 0 } 
       ] 
    }, 
    { 
     _id: 200, 
     question: "who is the eldest ?", 
     order: 2, 
     answers: [ 
        { _id: 201, answer: "Chris Griffin", points: 0 }, 
        { _id: 202, answer: "Meg Griffin", points: 100 }, 
        { _id: 203, answer: "Stewie Griffin", points: 0 } 
       ] 
    } 
    ] 
} 

我想要得到的只是有一個字段order: 1(所有其他問題將被隱藏)的問題,我也希望points場被隱藏。

我該怎麼做?

回答

1

您可以在聚合這樣的查詢有兩個$project階段實現這一目標:

db.collection.aggregate([ 
    { 
     $project:{ 
     questions:{ 
      $filter:{ 
       input:"$questions", 
       as:"qu", 
       cond:{ 
        $eq:[ 
        "$$qu.order", 
        1 
        ] 
       } 
      } 
     } 
     } 
    }, 
    { 
     $project:{ 
     "questions.answers.points":0 
     } 
    } 
]) 

此輸出:

{ 
    "_id" : 1, 
    "questions" : [ 
     { 
      "_id" : 100, 
      "question" : "who is the eldest ?", 
      "order" : 1, 
      "answers" : [ 
       { 
        "_id" : 101, 
        "answer" : "Bart Simpson" 
       }, 
       { 
        "_id" : 102, 
        "answer" : "Lisa Simpson" 
       }, 
       { 
        "_id" : 103, 
        "answer" : "Maggie Simpson" 
       } 
      ] 
     } 
    ] 
} 
+0

謝謝費利克斯!我需要使用'meteorhacks:聚合'的權利? –

+1

@SegevLahav是的,這應該適用於'meteorhacks:aggregate' – felix