问题
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