How to search sub arrays in MongoDB

♀尐吖头ヾ 提交于 2019-12-20 05:41:23

问题


I have this MongoDB collection:

{ "_id" : ObjectId("123"), "from_name" : "name", "from_email" : "email@mxxxx.com", "to" : [  {  "name" : "domains",  "email" : "domains@xxx.com" } ], "cc" : [ ], "subject" : "mysubject" }

My goal is to search in this collection by the "to" with some email.


回答1:


If you only want one field then MongoDB has "dot notation" for accessing nested elements:

db.collection.find({ "to.email": "domains@example.com" })

And this will return documents that match:

For more that one field as a condition, use the $elemMatch operator

db.collection.find(
    { "to": { 
        "$elemMatch": { 
            "email": "domains@example.com",
            "name": "domains",
        }
    }}
)

And you can "project" a single match to just return that element:

db.collection.find({ "to.email": "domains@example.com" },{ "to.$": 1 })

But if you expect more than one element to match, then you use the aggregation framework:

db.collection.aggregate([
    // Matches the "documents" that contain this
    { "$match": { "to.email": "domains@example.com" } },

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

    // Matches only those elements that match
    { "$match": { "to.email": "domains@example.com" } },

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

])

All fun ways to match on and/or "filter" the content of an array for matches if required.



来源:https://stackoverflow.com/questions/25990917/how-to-search-sub-arrays-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!