Mongoose只查找并返回文档的一部分

时间:2016-03-06 14:20:41

标签: node.js mongodb mongoose

我的对象:

[
    {
      "_id": "568ad3db59b494d4284ac191",
      "name": "Test",
      "groups": [
        {
          "number": "1",
          "name": "GroupTest",
          "_id": "568ad3db59b494d4284ac19b",
          "orders": [
            {
              "date": "2016-03-06T13:07:40.990Z",
              "_id": "56dc2b9c1d47772806e4f0f4",
              "readings": [
                {
                  "readingid": "568ad3db59b494d4284ac1a5",
                  "_id": "56dc2b9c1d47772806e4f0fc"
                },
                {
                  "readingid": "568ad3db59b494d4284ac1a4",
                  "_id": "56dc2b9c1d47772806e4f0fb"
                },
                {
                  "readingid": "568ad3db59b494d4284ac1a3",
                  "_id": "56dc2b9c1d47772806e4f0fa"
                },
                {
                  "readingid": "568ad3db59b494d4284ac1a2",
                  "_id": "56dc2b9c1d47772806e4f0f9"
                },
                {
                  "readingid": "56d48ae1a0f6e04413fc8b3e",
                  "_id": "56dc2b9c1d47772806e4f0f8"
                },
                {
                  "readingid": "56d48ae1a0f6e04413fc8b3f",
                  "_id": "56dc2b9c1d47772806e4f0f7"
                },
                {
                  "readingid": "568ad3db59b494d4284ac1a1",
                  "_id": "56dc2b9c1d47772806e4f0f6"
                },
                {
                  "readingid": "568ad3db59b494d4284ac1a0",
                  "_id": "56dc2b9c1d47772806e4f0f5"
                }
              ]
            },
            {....}
          ]
        },
        {....}
      ]
    },
    {.....}
]

我需要使用带有_id的组中的_id:“56dc2b9c1d47772806e4f0f4”查找订单:_id:“568ad3db59b494d4284ac19b”在客户端对象中使用_id:“568ad3db59b494d4284ac191”并且我只想获得该订单子对象,而不是整个客户端对象

我尝试过类似的事情:

Client.find(
{_id: "568ad3db59b494d4284ac191", groups._id: "568ad3db59b494d4284ac19b", groups.orders._id:"56dc2b9c1d47772806e4f0f4"},
{groups.orders:{$elemMatch:{_id: "56dc2b9c1d47772806e4f0f4"}}})

Antoher尝试没有成功:

Client.find(
{_id: req.company, groups:ObjectId(req.params.groupId)},
{"groups.orders":{$elemMatch:{_id: ObjectId(req.params.orderId)}}}, function(e,company){
    if(!e) {
      console.log(company);
    }
});

1 个答案:

答案 0 :(得分:0)

mongo是一个以文档为导向的"数据库,所以它提供的所有正常操作和查询都返回"文件"而不是"文档的部分",所以使用普通的查询方法,没有办法只获得一个子对象。

您可以使用mongo聚合框架来实现您想要的内容(https://docs.mongodb.org/manual/reference/operator/aggregation/),使用两个$unwindhttps://docs.mongodb.org/manual/reference/operator/aggregation/unwind/。 这将为每个order生成一个文档,然后使用$match过滤掉您需要的文档。

但重新考虑您的数据模型可能更好。如果您确实只需要查询和检索订单,而无需获取整个客户端对象,那么最好将订单存储在自己的集合中,并使用对组和客户端的引用。