Mongodb find a value inside the array

拜拜、爱过 提交于 2019-12-25 01:32:12

问题


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 native query

Person.native(function(err,collection){

collection.find( emails : { "$in" : "a@a.com"} , function(err , result){
    //code
 });

});

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) { });

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".

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".

How can i do that?

But I didn't get the required output using the above query. Please help. Thanks a lot.


回答1:


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) {

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.

Also see the $elemMatch operator for it's uses.



来源:https://stackoverflow.com/questions/22708069/mongodb-find-a-value-inside-the-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!