聚合函数使用Mognodb和Node.js返回空白数组值

时间:2019-09-06 09:35:26

标签: node.js mongodb aggregate

我正在使用MongoDB aggregate方法从集合中获取数据,但是它返回了空白值。

  

collection :: restaurant-

{cosine:"America",name:"brooklyn","grades":[{status:"A","amount":500},{status:"B","amount":300},{status:"C","amount":150}]},
{cosine:"Indian",name:"Arya","grades":[{status:"A","amount":1000},{status:"B","amount":700},{status:"C","amount":400}]},
{cosine:"Thai",name:"Crooks","grades":[{status:"A","amount":5000},{status:"B","amount":3000},{status:"C","amount":200}]},
{cosine:"Chinise",name:"China sea","grades":[{status:"A","amount":1500},{status:"B","amount":890},{status:"C","amount":500}]}

以上是我的收集数据。我正在使用以下代码来获取匹配的记录。

db.restaurant.aggregate([
            {$match:{grades:{status:"A"}}}
    ]).toArray((err, docs)=>{
        if (err) {
            console.log('err',err);
            res.send(err);
        }else{
            console.log('docs',docs);
            res.send(docs);
        }
    })

在控制台中,我得到的是空白数组。我需要获取其grades status=A的记录。

2 个答案:

答案 0 :(得分:0)

您可以通过$ unwind尝试此操作,$ unwind将对象/数组拉出一侧,以便我们可以匹配嵌套对象中的任何条件。

db.restaurant.aggregate([
  { '$unwind': '$grades' },
  { $match: { grades: { status: "A" } } }
]).toArray((err, docs) => {
  if (err) {
    console.log('err', err);
    res.send(err);
  } else {
    console.log('docs', docs);
    res.send(docs);
  }
})

答案 1 :(得分:0)

这是您的查询

db.getCollection("stackans").aggregate([
    {
   $unwind : "$grades"   
    },  {
        $match: {
            "grades.status": "A"
        }
    }
]);

OutPut

/* 1 */
{
    "_id" : ObjectId("5d7275504a3464edefcab2f5"),
    "cosine" : "America",
    "name" : "brooklyn",
    "grades" : {
        "status" : "A",
        "amount" : 500
    }
}

/* 2 */
{
    "_id" : ObjectId("5d72756d4a3464edefcab2fb"),
    "cosine" : "Indian",
    "name" : "Arya",
    "grades" : {
        "status" : "A",
        "amount" : 1000
    }
}

/* 3 */
{
    "_id" : ObjectId("5d7275824a3464edefcab2ff"),
    "cosine" : "Thai",
    "name" : "Crooks",
    "grades" : {
        "status" : "A",
        "amount" : 5000
    }
}

/* 4 */
{
    "_id" : ObjectId("5d7275924a3464edefcab301"),
    "cosine" : "Chinise",
    "name" : "China sea",
    "grades" : {
        "status" : "A",
        "amount" : 1500
    }

}