[英]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){
});
Person.native(function(err,collection){
collection.find( emails : { "$in" : "a@a.com"} , function(err , result){
//code
});
Now i tried using OR as below. 现在我尝试使用OR如下。
Person.findOne({
"or": [
{"emails.a": "a@a.com" },
{"emails.b": "a@a.com" },
{"emails.c": "a@a.com" }
]
}, function(err,doc) { });
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. 如果“emails.a”有“a@a.com”,那么doc应返回输出。 else search for "a@a.com" continues in "emails.b" or "emails.c".
否则在“emails.b”或“emails.c”中继续搜索“a@a.com”。
How can i do that? 我怎样才能做到这一点?
But I didn't get the required output using the above query. 但是我没有使用上面的查询获得所需的输出。 Please help.
请帮忙。 Thanks a lot.
非常感谢。
Your array contains a sub-document with keys a
, b
and c
. 您的数组包含一个带有键
a
, b
和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) {
If you are expecting to do this across the different fields you combine this with $or
: 如果您希望在不同的字段中执行此操作,请将其与
$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. 请注意,这与“文档”匹配,而不仅仅是数组的成员。
Also see the $elemMatch
operator for it's uses. 另请参阅
$elemMatch
运算符以了解它的用途。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.