【问题标题】:How to publish certain element in array with some fields hidden?如何在隐藏某些字段的数组中发布某些元素?
【发布时间】:2017-08-31 10:36:02
【问题描述】:

我有这个测验文件:

{
  _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 字段被隐藏。

我该怎么做?

【问题讨论】:

    标签: meteor publish-subscribe


    【解决方案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"
                    }
                ]
            }
        ]
    }
    

    【讨论】:

    • 谢谢菲利克斯!我需要使用meteorhacks:aggregate 对吗?
    • @SegevLahav 是的,这应该适用于 meteorhacks:aggregate
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多