为什么我无法获得完整的文档表单数组?

时间:2016-04-13 13:36:18

标签: arrays mongodb mongodb-query

我将此文档存储在我的收藏中:

{ "_id" : ObjectId("5707b95b8415b224a48a0b2d"), 
  "companyId" : ObjectId("570269639caabe24e4e4043e"), 
   "descriptions" : [ 
                     { "id" : ObjectId("5707b95b8415b224a48a0b2a"), "description" : "test" },
                     { "id" : ObjectId("570cd8164fff3a20f88c0dc9"), "description" : "test1" },
                     { "id" : ObjectId("570ce6ba4fff3a052c8c570f"), "description" : "etr" },
                     { "id" : ObjectId("570cf1b64fff3a1a14d71716"), "description" : "43" },
                     { "id" : ObjectId("570cf1b64fff3a1a14d71717"), "description" : "43" },
                     { "id" : ObjectId("570cf1b64fff3a1a14d71719"), "description" : "345" } 
                    ],
    "options" : [
                 { "descriptionId" : ObjectId("5707b95b8415b224a48a0b2a"), "description" : "test" },
                 { "descriptionId" : ObjectId("5707b95b8415b224a48a0b2a"), "description" : "test1" } 
                ]
}

现在我尝试从options数组中获取与descriptionId匹配的对象,这就是我的做法

db.CustomFields.find({companyId: ObjectId("570269639caabe24e4e4043e")},{"options.descriptionId": ObjectId("5707b95b8415b224a48a0b2a")})

但结果仅包含descriptionId - 缺少description属性。

结果如下:

{ "_id" : ObjectId("5707b95b8415b224a48a0b2d"),
  "options" : [ 
               { "descriptionId" : ObjectId("5707b95b8415b224a48a0b2a") },
               { "descriptionId" : ObjectId("5707b95b8415b224a48a0b2a") } 
              ]
}

为什么我的查询没有从数组中返回完整的文档,而只是它的一部分?你能帮我推吗?

修改

这是我期望从查询

获得的
{ "_id" : ObjectId("5707b95b8415b224a48a0b2d"),
  "options" : [ 
               { "descriptionId" : ObjectId("5707b95b8415b224a48a0b2a", "description" : "test") },
               { "descriptionId" : ObjectId("5707b95b8415b224a48a0b2a", "description" : "test1") } 
              ]
}

2 个答案:

答案 0 :(得分:1)

试试这个

db.CustomFields.find({companyId:ObjectId(" 570269639caabe24e4e4043e")," options.descriptionId":ObjectId(" 5707b95b8415b224a48a0b2a")})

答案 1 :(得分:1)

您需要将"options.descriptionId"的其他查询与companyId查询一起包含在内,并使用投影返回您想要的数组。

以下显示了这一点:

db.customFields.find(
    {
        "companyId": ObjectId("570269639caabe24e4e4043e"),
        "options.descriptionId": ObjectId("5707b95b8415b224a48a0b2a")
    }, 
    { "options": 1 }
);

<强>输出

{
    "_id" : ObjectId("5707b95b8415b224a48a0b2d"),
    "options" : [ 
        {
            "descriptionId" : ObjectId("5707b95b8415b224a48a0b2a"),
            "description" : "test"
        }, 
        {
            "descriptionId" : ObjectId("5707b95b8415b224a48a0b2a"),
            "description" : "test1"
        }
    ]
}