0

填充时我有如下问题对象。

{
   title: "Question Title",
   category: {
      "_id": "562ddc95a93f89e012554be1",
      "name": "Category",
      "parent": {
           "_id" : "562ddc95a93f89e012554be1", 
           "name": "Parent Category"
       }
   }
}

和下面的类别对象

{
   "_id" : "562ddc95a93f89e012554be1",
   "name": "Category Name",
   "parent": "562ddc95a93f89e012554be1"
}

我希望得到特定父类别中的问题。

我尝试这样的查询,但它不起作用。

Questions
   .count("category.parent._id":_id)

我怎样才能做到这一点?这在猫鼬中可能吗?

4

1 回答 1

1

您可以像这样构建对 count 的使用:

 Questions.count({"category.parent._id" : _id}, function(err, c){
         if(err) return err;
         console.log('Count is ' + c);
 });

查看文档中的各种可能性。

为了在 mongodb shell 中进行测试,我在一个名为 questions 的集合中创建了以下两个文档。

{
    "title" :"Question1",
    "category":{
        "_id":"123",
        "name" : "category 1",
        "parent" : {
            "_id" : "567",
            "name" : "parent category"
        }
    }
},
{
      "title" :"Question2",
      "category":{
          "_id":"124",
          "name" : "category 1",
          "parent" : {
              "_id" : "568",
              "name" : "parent category"
          }
      }
}

此查询应返回 1:

db.questions.count({"category.parent._id":"568"})

您应该将条件放在双引号中。如果不使用它可能会产生错误。

于 2015-11-02T14:20:02.137 回答