如何在 MongoDB 中搜索子数组 [英] How to search sub arrays in 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 有 "dot notation" 用于访问嵌套元素:
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 })
但是如果你期望 more 比 one 元素匹配,那么你使用聚合框架:
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屋!