使用数组中的一条记录在MongoDB中查找匹配记录

时间:2019-09-24 01:11:16

标签: mongodb

我有一组联系人,我需要找到一个或多个与数组中的记录匹配的联系人。

该数组如下所示:

[
    { linkType: "email", "bob@example.com" },
    { linkType: "email", "joan@example.com" }
    { linkType: "customerID", "12345" }
]

联系人记录(已减少)如下:

{
    "code": "cust01",
    "contactLink": [
        {
            "linkType": "email",
            "value": "joe@example.com"
        },
        {
            "linkType": "customerID",
            "value": "12345"
        }
    ],
    "name": "joe bloggs"
}

我只需要数组中的一个匹配项-但两个字段都需要匹配,结果可能返回多个记录。如何在不执行多次查找(迭代数组)的情况下做到这一点?

感谢您的时间。

1 个答案:

答案 0 :(得分:0)

我们可以使用$elemMatch对数组元素应用过滤器。以下是一个示例:

db.collection.find({
    "contactLink":{
        $elemMatch:{
            "linkType": "email",
            "value": "joe@example.com"
        }
    }
}).pretty()

数据集:

{
    "_id" : ObjectId("5d89b84c9c5291d5f4963e7d"),
    "code" : "cust01",
    "contactLink" : [
        {
            "linkType" : "email",
            "value" : "joe@example.com"
        },
        {
            "linkType" : "customerID",
            "value" : "12345"
        }
    ],
    "name" : "joe bloggs"
}
{
    "_id" : ObjectId("5d89b84c9c5291d5f4963e7e"),
    "code" : "cust01",
    "contactLink" : [
        {
            "linkType" : "email",
            "value" : "josh@example.com"
        },
        {
            "linkType" : "customerID",
            "value" : "12345"
        }
    ],
    "name" : "joe bloggs"
}

输出:

{
    "_id" : ObjectId("5d89b84c9c5291d5f4963e7d"),
    "code" : "cust01",
    "contactLink" : [
        {
            "linkType" : "email",
            "value" : "joe@example.com"
        },
        {
            "linkType" : "customerID",
            "value" : "12345"
        }
    ],
    "name" : "joe bloggs"
}