我如何搜索子阵列MongoDB中

我如何搜索子阵列MongoDB中

问题描述:

有这样的MongoDB集合:我如何搜索子阵列MongoDB中

{ "_id" : ObjectId("123"), "from_name" : "name", "from_email" : "[email protected]", "to" : [ { "name" : "domains", "email" : "[email protected]" } ], "cc" : [ ], "subject" : "mysubject" } 

我的目标是通过这个集合中搜索“到”一些电子邮件。

如果只想一个场则MongoDB的具有"dot notation"访问嵌套的元素:

db.collection.find({ "to.email": "[email protected]" }) 

,这将返回匹配的文件:

对于更多一个字段作为一个条件,使用$elemMatch运营商

db.collection.find(
    { "to": { 
     "$elemMatch": { 
      "email": "[email protected]", 
      "name": "domains", 
     } 
    }} 
) 

而且你可以在“项目”一比赛刚刚返回元素:

db.collection.find({ "to.email": "[email protected]" },{ "to.$": 1 }) 

但是,如果你指望超过一个元素相匹配,那么您使用聚合框架:

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

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

    // Matches only those elements that match 
    { "$match": { "to.email": "[email protected]" } }, 

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

]) 

所有有趣的方式匹配和/或“过滤”数组的内容匹配,如果需要。

+0

Thanky很多。优秀的答案。 – 2014-09-23 13:47:19