如果只想一個場則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" }
}}
])
所有有趣的方式匹配和/或「過濾」數組的內容匹配,如果需要。
Thanky很多。優秀的答案。 – 2014-09-23 13:47:19