Mongodb在数组中找到一个值 [英] Mongodb find a value inside the array
问题描述
如果我有此架构...
If I have this schema...
person = {
emails : Array
}
这些值存储在电子邮件数组中,如下所述:
The values are stored in emails array as mentioned below:
emails : [{ a : "a@a.com" , b: "b@b.com" , c : "c@c.com" }]
现在我尝试了以下提到的查询,
Now i tried the below mentioned queries ,
Person.findOne({emails : "a@a.com"}).exec(function(err,person){
});
Mongodb本机查询
Person.native(function(err,collection){
collection.find( emails : { "$in" : "a@a.com"} , function(err , result){
//code
});
});
修改后的问题
现在我尝试按如下所示使用OR.
});
EDITED QUESTION
Now i tried using OR as below.
Person.findOne({
"or": [
{"emails.a": "a@a.com" },
{"emails.b": "a@a.com" },
{"emails.c": "a@a.com" }
]
}, function(err,doc) { });
实际上,我必须检查"emails.a"是否具有"a@a.com",如果不仅如此,我还必须查找"emails.b"或"emails.c"是否具有"a@a.com" .
Actually , i have to check "emails.a" have "a@a.com" , if not only , i have to find whether "emails.b" or "emails.c" have "a@a.com".
如果"emails.a"具有"a@a.com",则文档应返回输出. 否则,继续在"emails.b"或"emails.c"中搜索"a@a.com".
if "emails.a" have "a@a.com" , then the doc should return the output. else search for "a@a.com" continues in "emails.b" or "emails.c".
我该怎么做?
但是我没有使用上面的查询得到所需的输出.请帮忙.非常感谢.
But I didn't get the required output using the above query. Please help. Thanks a lot.
推荐答案
您的数组包含一个键为a
,b
和c
的子文档.为了匹配您想要的值,您需要指定此元素.
Your array contains a sub-document with keys a
, b
and c
. In order to match the value you want you need to specify this element.
Person.findOne({ "emails.a": "a@a.com" }, function(err,doc) {
如果希望在不同的字段中执行此操作,请将其与 $or
:
If you are expecting to do this across the different fields you combine this with $or
:
Person.findOne({
"$or": [
{"emails.a": "a@a.com" },
{"emails.b": "a@a.com" },
{"emails.c": "a@a.com" }
]
}, function(err,doc) {
请注意,这不仅与数组的成员匹配,而且与文档"匹配.
Please note that this is matching the "document" and not just the member of the array.
另请参见 $elemMatch
运算符.
Also see the $elemMatch
operator for it's uses.
这篇关于Mongodb在数组中找到一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!