MongoDB聚合迭代

时间:2018-11-09 16:31:12

标签: mongodb loops asynchronous mongodb-query aggregation-framework

我有一个收藏集:

{  
  "value" : "20",
  "type" : "square",
  "name" : "form1"
},
{
  "value" : "24",
  "type" : "circle",
  "name" : "form2"
},
{
  "value" : "12",
  "type" : "square",
  "name" : "form3"
}

此聚合:

let searchTerm = "form2"

db.myCollec.aggregate([
  { "$facet": {
    "data": [
      { "$match": { "name": searchTerm  }},
      { "$project": { "name": 1, "type": 1, "_id": 0 }}
    ]
  }},
  { "$project": {
    "name": {
      "$ifNull": [{ "$arrayElemAt": ["$data.name", 0] }, searchTerm ]
    },
    "type": {
      "$ifNull": [{ "$arrayElemAt": ["$data.type", 0] }, null]
    }
  }}
])

给出此结果:

{ "name" : "form2", "type" : "circle" }

如果我正在寻找不存在的“ form4”:

{ "name" : "form4", "type" : null }

现在我想对很多值进行处理,因此我尝试将它们放入数组中,然后在此数组上循环。根据javascript的异步属性,我尝试以下代码:

tab = [ "form2", "form4" ] 
for( var i =0; i<(tab.length);i++) { (function (i) {
searchTerm = tab[i]
db.myCollec.aggregate([
  { "$facet": {
    "data": [
      { "$match": { "name": searchTerm  }},
      { "$project": { "name": 1, "type": 1, "_id": 0 }}
    ]
  }},
  { "$project": {
    "name": {
      "$ifNull": [{ "$arrayElemAt": ["$data.name", 0] }, searchTerm ]
    },
    "type": {
      "$ifNull": [{ "$arrayElemAt": ["$data.type", 0] }, null]
    }
  }}
])
}) (i) }

没有结果... 如果我添加print(searchTerm),则这些值会很好地打印出来,但没有合计结果。

感谢您的帮助。

0 个答案:

没有答案