How i can find the word in this query params? - node.js

I'm trying to make a query that filters by a string param with this format:
filter: (status~contains~false~and~username~contains~'admin')
So, i need to make a search() in this request.input('filter') and search the word after the contains to make my query. I'm with difficulty to make the regex (i don't know if i really need a regex)
Something like:
if(request.input('filter').search('regex??'))
queryUsers.where('username', 'like', '%'+request.input('username')+'%')
Tried:
if(filter.search("username")){
let userName = filter.search(/?<=username~contains~).*$/g).replace("'", "")
console.log(userName)
//queryUsers.where('username', 'like', '%'+request.input('username')+'%')
}
But i receive:
Invalid regular expression: /?<=username~contains~).*$/: Nothing to
repeat

No need to use regular expression you can run like query as below -
Database.from('users').whereRaw('username Like ?', ['%'+request.input('username')+'%'])

Related

how to find a string in another one without using find() method in python

I have the following code:
def light():
result = collection1.find({"deviceName": })
lights_id = []
for x in result:
lights_id.append(x["_id"])
return lights_id
I need to fetch in a database for a device name containing the string light, and I need to fill it in the blank but I don't know how to do it in this case.
Assuming your collecyion1 is a mongodb collection, i think this should work
collection1.find({'deviceName': {'$regex': ".*light.*", '$options': 'i'}})
as mongodb supports regex, we are searching a text using regex in this case
./*light.* and passing option i so that the match is case insensetive.

How to search for a specific dynamic pattern of a field's in mongodb.?

I need to search mongodb collection for a specific pattern field. I tried using {$exists:true}; However, this gives results only if you provide exact field.
I tried using {$exists:true} for my field. But this does not give results if you give some pattern.
{
"field1":"value1",
"field2":"value2",
"field3":object
{/arjun1/pat1: 1,
/arjun2/pat2: 3,
/arjun3/pat3: 5
}
"field4":"value4",
}
From some field, I get the keys pat3 & field3. From this I would need to find out if the value /arjun3/pat3 exists in the document.
If I use {"field3./arjun3/pat3":{$exists:true}}, this would give me results. But the problem is I get only field3 and pat3 and I need to use some pattern matching like field3.*.pat3 and then use $expr or $exists; which I'm not exactly sure how to. Please help.
you could try something of this kind
db.arjun.find(
{"field3" : {
"$elemMatch" : { $and: [
{"arjun3.pat3" : {$exists:true}},
{"arjun3.pat3" : 5}
]
}}}
);
You can either go for regex (re module) for SQL like pattern matching, and compile your own custom wildcard. But if you don't want that then you can simple use the fnmatch module, it is a builtin library of python which allows wildcard matching for multiple characters (via*) or a single character (via ?).
import fnmatch
a = "hello"
print(fnmatch.fnmatch(a, "h*"))
OUTPUT:-
True

How to search full or partial match with first name and last name in mongodb

How to search full or partial match with first name and last name in mongodb?
I tried using this,
{"name":{ $regex: str, $options: 'i'}}
But it is only for full match of the string.
Can I use regex for partial match?
For this type of search better to create text index. mongo shell command to create text index for name field.
db.colectionName.createIndex( { name: "text" } );
then you can search using $text and $search
var text = 'John Test''
db.collectionName.find({ $text: { $search: text } });
for this query you will get if name contain john or test and this is case insensitive
I have to do this for my project, how does this work for you? {"name":new RegExp('^'+name, 'i')} you may need to encode the string first str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
Try this
{'name': {'$regex': '.*str.*', $options: 'i'}}
I have responded to similar question here, combining text index and regex pattern makes it work nicely. Note, text index is searching by terms so if you try to search for padavan by supplying pad you won't get what you are expecting having only text index in place.

Using a regex with text search in MongoDB

I have created a text index on the num field in the collection. Now while passing the string to search from the text index, I need to use a regex which has to be passed as a string to the $search variable.
My current query works fine but it doesn't work when I add a regex to it.
Current Query:
db.collection.find({$text:{$search:"1234 6789"}},{'id':1})
I need to add a regex/like query to the $search to make it something like
db.collection.find({$text:{$search:"/1234/ /6789/"}},{'id':1})
where I get all the values from the database that contain a pattern like "1234" OR "6789".
I did try the query but it gives me a $search needs a String error:
db.collection.find({$text:{$search:/1234/}},{'id':1})
To achieve this you should use the $regex MongoDB operator:
// Without options
db.collection.find({num: /1234|5678/i});
// Separate options property
db.collection.find({num: {$regex: /1234|5678/, $options: 'i'}});
To add multiple terms in the regex, use the | operator
$regex docs and examples
Edit:
For querying records using an array of values the $in operator can be used:
$in docs and examples

How do you do a contains query using the MongoDB node.js driver?

I'm trying to do a search on items that contain a certain substring, but I'm getting no results back (even though I know the data is right for the query, including case):
collection.find({name: "/.*" + keyword + ".*/"}).toArray(function(err, items)
Should that not match everything that contains the keyword? It just returns an empty object.
I'm just using the regular MongoDB driver in an ExpressJS app.
You need to build a regular expression first should try something like this:
var regex = RegExp("/.*" + keyword + ".*/")
Then pass in the variable to the query. I generally find it easier to do the query as a variable and pass that in:
var query = { FieldToSearch: new RegExp('^' + keyword) };
collection.find(query).toArray(...)
I've included the regex as a left rooted regex to take advantage of indexes (always recommended if possible for performance). For more take a look here:
http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-RegularExpressions
I did it like this
keyword = "text_to_search";
collection.find({name: {$Regex: keyword, $options:$i }})
I used i $i make the query case insensitive but u can use other options too
try this:
var keyword = req.params.keywords;
var regex = RegExp(".*" + keyword + ".*");
Note.find({noteBody: regex, userID: userID})
I got the keywords from the request parameters and I want to search from the noteBody with these keywords, now the keywords is a variable. If you want to put a variable in the database find, the format must be var regex = RegExp("." + keyword + "."). Hope this helps. Thanks

Resources