如何在mongodb中找到匹配的记录?

我在我的collections中有一个记录,我想获取身份为1的人的详细信息。但我得到的细节是2次而不是1次。

db.mycollection.insert({"person" : [ { "id":1, "details" : { "name" : "Aswini", "Age" : 10 }}, { "id":2, "details" : { "name" : "Mahesh", "Age" : 11}}]}) 

然后跑

  > db.mycollection.findOne({"person.id":1},{"person.details":1,"_id":0}) 

结果是:

  { "person" : [ { "details" : { "name" : "Aswini", "Age" : 10 } }, { "details" : { "name" : "Mahesh", "Age" : 11 } } ] } 

但我需要如下:

  { "person" : [ { "details" : { "name" : "Aswini", "Age" : 10 } } ] } 

不明白哪里弄错了。 请你帮忙。 我使用的是MongoDB,Java

这是过滤多级嵌入文档的行为,通常匹配filter将返回整个文档,而不是子集。

通常positional operator $用于匹配updates中的子文档。 但该function尚未在返回说明符中实现。

mongo中已经有一个突出的问题支持在字段中的位置($)运算符返回说明符 。 (如果你真的需要这个function,请登录投票)

所以你必须重新设计你的架构来处理这个,可能是这样的

 db.test.insert({"person" : [ { "id":1, "details" : { "name" : "Aswini", "Age" : 10 }}]}) db.test.insert({"person" : [ { "id":2, "details" : { "name" : "Mahesh", "Age" : 11}}]}) db.test.find({"person.id":1},{'person.details':1}) 

person是一个arrays。 如果你想获得这个数组的第一个元素,你应该使用$ slice

 db.mycollection.findOne({"person.id":1},{"person":{$slice:[0,1]},"_id":0})