如何在MongoDB中搜索子数组 [英] How to search sub arrays in MongoDB

查看:53
本文介绍了如何在MongoDB中搜索子数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个MongoDB集合:

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.

推荐答案

如果您只想一个字段,则MongoDB具有,用于访问嵌套元素:

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

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

这将返回匹配的文档:

更多将该字段作为条件,请使用 $elemMatch 运算符

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.

这篇关于如何在MongoDB中搜索子数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆