How to search sub arrays in MongoDB

2020-05-03 11:47发布

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条回答
放荡不羁爱自由
2楼-- · 2020-05-03 12:13

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.

查看更多
登录 后发表回答