简体   繁体   中英

In mongoDb, how to get the entire record if a string input matches any array element (an array is a property of the records in this case)

Consider following record in db:

{
 name:"potato",
 age:"404",
 hobbies: ["brains", "zombieesss", "eat guitar"]
},

{
 name:"tom",
 age:"4",
 hobbies: ["guitar", "cooking", "soccer"]
}

What I want to achieve:

  1. if a certain input is "guitar", both records must show.
  2. if the input is "soccer" the second record must show.
  3. input can also be ["cooking", "soccer"] for which the second record must show.

I have thought of:-

Get the "hobbies" of all records then pass each of the arrays to a function that would give me the required records but it seems like the worst way to do it.

You can do it with $regex . Try the following queries:

db.collection.find( { hobbies: {$regex: "(.*guitar.*)"} } )

db.collection.find( { hobbies: {$regex: "(.*cooking.*)|(.*soccer.*)"} } )

".*" in regex query means match zero or more occurrences of any character

For your input you can create regex query with such code:

var input = ["cooking", "soccer"];
var regex = input.map(function(item){ return "(.*" + item + ".*)" }).join('|');
db.collection.find( { hobbies: {$regex: regex} } )

Say you form an array from your database table (though exaclty I don't know how you storing it), then

 function filterEl(arr, what){ return arr.filter(function(el){ return el.hobbies.join(",").indexOf(what) != -1; }); } var x = [{ name:"potato", age:"404", hobbies: ["brains", "zombieesss", "eat guitar"] }, { name:"tom", age:"4", hobbies: ["guitar", "cooking", "soccer"] }]; console.log(filterEl(x, "guitar")); // will return 2 elements console.log(filterEl(x, "soccer")); // will return the last element. 

Your question is still not so clear to me but what i understood is if the input (about hobbies) present in the input array,then print the hobies.

Here i will store the hobies in a variable if it matches.

let say input:

var a="guitar"

$.each(myObj,function(k,v){

    if(v.hobies.indexOf(a) > -1){
       // string present in an array you may proceed here...
}
});

Hope this answer may help you

尝试以下方法:

db.collection.find( { hobbies:{$or:[{/.*guitar.*/},{"cooking"},{"soccer"}]} })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM