如何在 MongoDB 中搜索子数组

2024-02-19

我有这个 MongoDB 集合:

{ "_id" : ObjectId("123"), "from_name" : "name", "from_email" : "[email protected] /cdn-cgi/l/email-protection", "to" : [  {  "name" : "domains",  "email" : "[email protected] /cdn-cgi/l/email-protection" } ], "cc" : [ ], "subject" : "mysubject" }

我的目标是通过“to”和一些电子邮件在此集合中进行搜索。


如果你只想one那么 MongoDB 有“点符号” http://docs.mongodb.org/manual/core/document/#document-dot-notation用于访问嵌套元素:

db.collection.find({ "to.email": "[email protected] /cdn-cgi/l/email-protection" })

这将返回匹配的文档:

For more将该字段作为条件,使用$elemMatch操作员

db.collection.find(
    { "to": { 
        "$elemMatch": { 
            "email": "[email protected] /cdn-cgi/l/email-protection",
            "name": "domains",
        }
    }}
)

你可以“投影”一个singlematch 仅返回该元素:

db.collection.find({ "to.email": "[email protected] /cdn-cgi/l/email-protection" },{ "to.$": 1 })

但如果你期望more than one元素匹配,然后使用聚合框架:

db.collection.aggregate([
    // Matches the "documents" that contain this
    { "$match": { "to.email": "[email protected] /cdn-cgi/l/email-protection" } },

    // De-normalizes the array
    { "$unwind": "$to" },

    // Matches only those elements that match
    { "$match": { "to.email": "[email protected] /cdn-cgi/l/email-protection" } },

    // Maybe even group back to a singular document
    { "$group": {
        "_id": "$_id",
        "from_name": { "$first": "$name" },
        "to": { "$push": "$to" },
        "subject": { "$first": "$subject" }            
    }}

])

如果需要,可以使用所有有趣的方法来匹配和/或“过滤”数组内容以进行匹配。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 MongoDB 中搜索子数组 的相关文章

随机推荐