2017-10-16 92 views
0

我有我的集合中的下列JSON文档:MongoDB的嵌套查询结构

{ 
    "_id": { 
     "$oid": "59e3a593734d1d62dcbe79c3" 
    } 
    "name": "UserNameKiran" 
    "notebooks": [ 
     { 
      "notebookname": "notebook1", 
      "notes": [ 
       { 
        "name": "noteName" 
       }, 
       { 
        "name": "noteName2" 
       } 
      ] 
     }, 
     { 
      "access": "public", 
      "notebookname": "notebook2", 
      "notes": [ 
       { 
        "name": "noteName" 
       }, 
       { 
        "name": "noteName2" 
       } 
      ] 
     } 
    ] 
}; 

我想检索所有来自特定用户和笔记本电脑“注意事项”。例如:“notebook1”的所有注释。

我试过下面的命令,但无法得到任何结果。

req.db.collection('usernotecollection').find({ 
     "_id": ObjectId(req.params.userId), 
     "notebooks": { 
      "$elemMatch": { 
       "notebookname": "notebook1" 
      } 
     } 
    }, {notes:1}).toArray(function (err, results) { 
     console.log(results); 
    }); 

它只是返回给我的object_id而没有其他的结果。我错过了什么?

回答

0

您提供给find()呼叫的第二个参数是:{notes:1}

这是一种投影,它告诉MongoDB的返回名为notes的属性,但有文档中名为notes使投影仅返回默认属性没有属性:_id

也许你打算在{notebooks:1}上投影呢?虽然这会返回所有内容,因此在功能上等同于不提供投影。

为了更清楚些,你可以运行下面的命令,你会看到,他们都返回相同的响应:

req.db.collection('usernotecollection').find({ 
     "_id": ObjectId(req.params.userId), 
     "notebooks": { 
      "$elemMatch": { 
       "notebookname": "notebook1" 
      } 
     } 
    }).toArray(function (err, results) { 
     console.log(results); 
    }); 

req.db.collection('usernotecollection').find({ 
     "_id": ObjectId(req.params.userId), 
     "notebooks": { 
      "$elemMatch": { 
       "notebookname": "notebook1" 
      } 
     } 
    }, {notebooks:1}).toArray(function (err, results) { 
     console.log(results); 
    }); 

但是,如果你真正想要的是notes属性与notebooks子文件,那么你会想在'notebooks.notes': 1项目。下面的示例项目上notebooks.notes和排除默认_id突起,从而只返回notebooks.notes

req.db.collection('usernotecollection').find({ 
     "_id": ObjectId(req.params.userId), 
     "notebooks": { 
      "$elemMatch": { 
       "notebookname": "notebook1" 
      } 
     } 
    }, {'notebooks.notes':1, '_id': 0}).toArray(function (err, results) { 
     console.log(results); 
    }); 
+0

感谢您的明确解释。但是,我无法获得特定笔记本的笔记。出于某种原因,“notebookname”:“notebook1”的匹配没有发生。 –

+0

Tehre在名为'notebookname'的'notebooks'子文件中没有属性,也许你的意思是'notes.name'。一般来说,这种形式的问题(如何从这个文档中获得x?)最好用(1)样本文件; (2)你尝试过的查询的例子和(3)**所需的输出**。 – glytching

+0

谢谢我能解决我的问题 –

0

为了过滤可以使用$elemMatch运营商在查询中的突出部分数组元素。

req.db.collection('usernotecollection').find({ 
    // filter 
    "_id": ObjectId(req.params.userId) 
}, { 
    // projection 
    "notebooks": { 
     "$elemMatch": { 
      "notebookname": "notebook1" 
     } 
    } 
}).toArray(function (err, results) { 
    console.log(results); 
});