【问题标题】:How to pull embedded docs from MongoDB query into array?如何将嵌入式文档从 MongoDB 查询中提取到数组中?
【发布时间】:2017-01-21 08:05:44
【问题描述】:

我有一个变量var correctAnswers;

在我的 MongoDB 中,我有以下文档(如下)。我正在尝试编写一个查询,该查询从“测验”字段中获取所有“正确”字段并将它们放入自己的数组中,因此我可以将该数组设置为等于var correctAnswers;

"title" : "Economics questions"
"quiz": "[{
          "question": "Which of these involves the analysis of of a business's financial statements, often used in stock valuation?",
          "choices": ["Fundamental analysis", "Technical analysis"],
          "correct": 0
        }, {
          "question": "What was the name of the bond purchasing program started by the U.S. Federal Reserve in response to the 2008 financial crisis?",
          "choices": ["Stimulus Package", "Mercantilism", "Quantitative Easing"],
          "correct": 2
        }, {
          "question": "Which term describes a debt security issued by a government, company, or other entity?",
          "choices": ["Bond", "Stock", "Mutual fund"],
          "correct": 0
        }, {
          "question": "Which of these companies has the largest market capitalization (as of October 2015)?",
          "choices": ["Microsoft", "General Electric", "Apple", "Bank of America"],
          "correct": 2
        }, {
          "question": "Which of these is a measure of the size of an economy?",
          "choices": ["Unemployment rate", "Purchasing power index", "Gross Domestic Product"],
          "correct": 2
        }]"

我应该怎么做,或者有人能指出我正确的方向吗?我已经尝试过预测,但我应该进行聚合吗?感谢您的帮助。

为清楚起见进行编辑:我在此示例中查找的输出是一个数组,[0,2,0,2,2]

【问题讨论】:

  • “测验”字段中的“正确”字段是什么意思?请定义您想要的输出,以便我可以提供帮助
  • 见这里:stackoverflow.com/questions/4969768/… 在 MongoDB 中还没有一个很好的方法,它已经成为 JIRA 项目有一段时间了。
  • @Himanshusharma 感谢您的回复,我的意思是数组中每个对象中名为“正确”的字段。编辑:这种情况下的输出将是一个数组,[0,2,0,2,2]
  • 在你尝试做的时候在 node.js 中提供一些代码。你觉得用猫鼬吗?
  • 您似乎正在尝试获取一个数组以便生成平均值?我也在追求同样的事情,但还没有找到好的解决方案。

标签: node.js mongodb express


【解决方案1】:

你可以得到这个结果 [{correct:0},{correct:2},{correct:0},{correct:2}] 但 [0,2,0,2,2] 类型的结果是不可能的,除非我们使用 distinct

db.quiz.aggregate( // 初始文档匹配(使用索引,如果有合适的可用) { $匹配:{ "title" : "经济学问题" }},

// Convert embedded array into stream of documents
{ $unwind: '$quiz' },

    },

// Note: Could add a `$group` by _id here if multiple matches are expected

// Final projection: exclude fields with 0, include fields with 1
{ $project: {
    _id: 0,
    score: "$quiz.correct"
}} )

【讨论】:

    【解决方案2】:
    db.users.find( { }, { "quiz.correct": 1,"_id":0 } ) 
    

    // 上面的查询将返回以下输出:

    {
            "quiz" : [
                    {
                            "correct" : 0
                    },
                    {
                            "correct" : 2
                    },
                    {
                            "correct" : 0
                    },
                    {
                            "correct" : 2
                    },
                    {
                            "correct" : 2
                    }
            ]
    }
    

    根据节点js中的要求处理此输出。

    【讨论】:

      【解决方案3】:

      试试这个:

      db.getCollection('quize').aggregate([
      {$match:{_id: id }},
      {$unwind:'$quiz'}, 
      {$group:{
      _id:null, 
      score: {$push:"$quiz.correct"} 
      }}
      ])
      

      它会给你预期的输出。

      【讨论】:

        【解决方案4】:

        通过聚合实现此目的的一种方法

        db.collectionName.aggregate([
             // use index key in match pipeline,just for e.g using title here
            { $match: { "title" : "Economics questions" }},
            { $unwind: "$quiz" },
            { $group: {
                  _id:null,
                  quiz: { $push:  "$quiz.correct" }
                } 
            },
            //this is not required, use projection only if you want to exclude/include fields 
            { 
                $project: {_id: 0, quiz: 1}
            } 
        ])
        

        上面的查询会给你以下输出

        {
            "quiz" : [ 0, 2, 0, 2, 2 ]
        }
        

        然后根据您的需要简单地处理此输出。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-03-24
          • 1970-01-01
          • 2021-08-07
          • 2015-02-06
          • 2020-03-23
          • 2011-05-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多