MongoDB:在文档中查找包含带有数组的子对象的对象的元素

时间:2017-12-11 03:39:52

标签: mongodb

我越来越困惑地发现mongodb在查询编写过程中是如何过于复杂和糟糕的设计,无论如何我在拥有数千条记录的数据库中都有这种文档:

db.messages.aggregate([{$limit: 1}]).pretty()
{
        "_id" : ObjectId("4f16fc97d1e2d32371003f42"),
        "body" : "Hey Gillette,\n\nThe heat rate is going to depend on the type of fuel and the construction \ndate of the unit.  Unfortunately, most of that info is proprietary.  \n\nChris Gaskill is the head of our fundamentals group and he might be able to \nsupply you with some of the guidelines.\n\n-Bass\n\n\n   \n\tEnron North America Corp.\n\t\n\tFrom:  Lisa Gillette                           04/05/2001 02:31 PM\n\t\n\nTo: Eric Bass/HOU/ECT@ECT\ncc:  \nSubject: Power Generation Question\n\nHey Bass,\n\nI have a question and I am hoping you can help me.  I am wanting to compile a \nlist of all the different types of power plants and their respective heat \nrates to determine some sort of generation ratio.\n\ni.e. Coal  4 mmbtu = 1 MW\n Simple Cycle 11 mmbtu = 1 MW\n\nPlease let me know if you can help me or point me to someone who can.  Just \nFYI...Bryan suggested that I call you so blame him as you curse me under your \nbreath right now.\n\nThanks,\nLisa\n\n",
        "filename" : "1045.",
        "headers" : {
                "Content-Transfer-Encoding" : "7bit",
                "Content-Type" : "text/plain; charset=us-ascii",
                "Date" : ISODate("2001-04-05T14:45:00Z"),
                "From" : "eric.bass@enron.com",
                "Message-ID" : "<2106897.1075854772243.JavaMail.evans@thyme>",
                "Mime-Version" : "1.0",
                "Subject" : "Re: Power Generation Question",
                "To" : [
                        "lisa.gillette@enron.com"
                ],
                "X-FileName" : "ebass.nsf",
                "X-Folder" : "\\Eric_Bass_Jun2001\\Notes Folders\\Sent",
                "X-From" : "Eric Bass",
                "X-Origin" : "Bass-E",
                "X-To" : "Lisa Gillette",
                "X-bcc" : "",
                "X-cc" : ""
        },
        "mailbox" : "bass-e",
        "subFolder" : "sent"
}

我需要从地址X找到记录Y的记录。

我设法用

捕捉“来自”记录
db.messages.find({"headers.From": "eric.bass@enron.com"}).pretty().count()

但是我无法获得To记录(我需要同时获得这些记录)。

要查询我尝试过的“收件人”字段:

db.messages.find({headers: {$elemMatch :{ "To": "lisa.gillette@enron.com"}}})

但它什么都不返回

我错过了什么? 感谢

1 个答案:

答案 0 :(得分:0)

$elemMatch - 要使用此运算符,我们需要给出数组元素和匹配运算符,在这种情况下它应该像

db.messages.find({"headers.To": {$elemMatch :{$eq:"lisa.gillette@enron.com"}}})
当我们为数组元素提供多个查询时, $ elemMatch是最佳选择。如果我们只在$ elemMatch表达式中指定一个条件,我们不需要使用$ elemMatch,而是可以使用find

db.messages.find({"headers.To": "lisa.gillette@enron.com"});