如何使用$ in运算符为对象数组返回匹配文档

时间:2016-02-22 12:48:36

标签: mongodb mongoose mongodb-query

我可以知道如何将$in运算符用于对象数组?并且只返回匹配文件?

这是我到目前为止所尝试过的,但我仍然无法得到我想要的东西。

我们说我的文件集看起来像这样

{
    "_id" : ObjectId("56824417fa32883c0335ce61"),
    "company_name" : "Pentagon",
    "deal_details" : [
        {
            "deals_name" : "hello",
            "deals_tag" : ["A","B","C"],
            "_id" : ObjectId("56c69da8a1f60804064abf0f")
        },
    {
            "deals_name" : "Hola",
            "deals_tag" : ["E","F","G"],
            "_id" : ObjectId("56c69da8a1f60804064abf0f")
        },
    ],
  "_id" : ObjectId("54824417fa32983c0335ce61"),
    "company_name" : "Oreo",
    "deal_details" : [
        {
            "deals_name" : "Bye",
            "deals_tag" : ["B"],
            "_id" : ObjectId("56c69da8a1f60804064abf0f")
        },
    {
            "deals_name" : "Ciao",
            "deals_tag" : ["H","I","J"],
            "_id" : ObjectId("56c69da8a1f60804064abf0f")
        },
    ]
}

我这样做

User.find({
  'deal_details.deals_tags': {
    $in: ["B"]
  }
 }
}, {'deal_details':1}).exec(function(err, deal) {
  if (err) {
    return res.status(500).send(err);
  }
  res.status(200).send(deal);
});

来自deal期望

            {
                "deals_name" : "hello",
                "deals_tag" : ["A","B","C"],
                "_id" : ObjectId("56c69da8a1f60804064abf0f")
            },
             {
                "deals_name" : "Bye",
                "deals_tag" : ["B"],
                "_id" : ObjectId("56c69da8a1f60804064abf0f")
            }

然而我得到了这个

            {
                "deals_name" : "hello",
                "deals_tag" : ["A","B","C"],
                "_id" : ObjectId("56c69da8a1f60804064abf0f")
            },
            {
                "deals_name" : "Hola",
                "deals_tag" : ["E","F","G"],
                "_id" : ObjectId("56c69da8a1f60804064abf0f")
            },
             {
                    "deals_name" : "Bye",
                    "deals_tag" : ["B"],
                    "_id" : ObjectId("56c69da8a1f60804064abf0f")
             },
             {
            "deals_name" : "Ciao",
            "deals_tag" : ["H","I","J"],
            "_id" : ObjectId("56c69da8a1f60804064abf0f")
             }

我可以知道有没有办法只返回匹配的文档? 感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

要在子文档中查找具有特定值的元素(这是您的情况)并过滤结果,您应该使用聚合框架。使用简单的查找文档是不可能的。

您可以在此处查看问题示例:How to filter array in subdocument with MongoDB

答案 1 :(得分:2)

你可以通过aggregation

来做到这一点
User.aggregate([{$unwind: '$deal_details'}, 
                {$match: {'deal_details.deals_tag': 'B'}}, 
                {$project: {deal_details: 1, _id: 0}}])