How to query mongo db to return all combinations of keys in a search term? - regex

In the mongo db are tags. I'm trying to pull out all the tags that would match starting from the beginning of a search term. Is it possible to achieve the following in a mongo query?
Mongo data:
[
{ tag: '123' },
{ tag: '1234' },
{ tag: '123456' },
{ tag: '987' },
{ tag: '555' }
]
Query search term = '12349339'
Result desired:
[
{ tag: '123'},
{ tag: '1234' }
]
or
[
{ tag: '1234' }
]
I've tried regex expressions to no avail as using (^) would only be useful if the longer search term was in the db and I was searching using a substring.
Update: Here's my regex attempt for anyone trying this approach.
tags.find({tag: {$regex: '^12349339*'}})
Returns nothing. If I wanted all tags that match '123' then this kind of query would work.
tags.find({tag: {$regex: '^123'}})
Returns:
[
{ tag: '123' },
{ tag: '1234' },
{ tag: '123456' }
]
But I wanted the reverse. So, figured I needed an aggregate function or something.

You could do:
{
$where: "'12349339'.indexOf(this.tag) == 0"
}
Obligatory performance note on using $where: The $where provides greater flexibility, but requires that the database processes the JavaScript expression or function for each document in the collection.
https://docs.mongodb.com/manual/reference/operator/query/where/

Related

Wiremock urlPattern with query param regex matching

I have the below wiremock setup & trying to set up the urlPattern matching using regex.
{
"scenarioName": "CPM Get Entitlements:Error - CPM_10000 - DOWNSTREAM_ERROR - Status 500",
"request": {
"method": "GET",
"urlPattern": "<REGEX>"
},
"response": {
"status": 500,
"body": "{\"code\": \"CPM_10000\",\"description\": \"some description\"}"
}
}
My URLs could be any one of these two.
http://localhost:8091/household/7c4c5cb4-ed2e-4fde-a774-66294698c035/entitlements
http://localhost:8091/household/7c4c5cb4-ed2e-4fde-a774-66294698c035/entitlements?includeFutureDated=true
I have tried various REGEX patterns like the one below but non of them works for 2nd URL with query param. I am able to construct REGEX that works in the text editor or in java but it seems not to be working in wiremock config file.
REGEX
/household/.+/entitlements(.*)
/household/.+/entitlements(\?includeFutureDated=true)
/household/.+/entitlements(?includeFutureDated=true)
Is there a way to fix this in wiremock?
I find it easier to match on urlPathPattern instead of urlPattern in this case, and then have a separate queryParameters matcher.
{
"scenarioName": "CPM Get Entitlements:Error - CPM_10000 - DOWNSTREAM_ERROR - Status 500",
"request": {
"method": "GET",
"urlPathPattern": "/househould/.+/entitlements", // this should match your URL
"queryParameters": {
"includeFutureDated": {
"or": [
{ "matches": "true" }, // update this to change your query parameter matching
{ "absent": true }, // this allows for a match when the query parameter is absent
],
},
},
},
"response": {
"status": 500,
"body": "{\"code\": \"CPM_10000\",\"description\": \"some description\"}"
}
}

Regex for multiple JSON string

I am trying to work around regex expression for a complicated json string (multiple nested objects).
Here's the json string
{
group: [],
lists: {
customer: {
lists: {
"13067": {
id: "13067",
featured: { enable: false },
},
},
},
},
}
Question is how to get value of 'id'? I tried /\"id\":\"(\d+)"/ but this wont work. Plz help!
rgds.
Are you looking for this?
id\s*:\s*\"(\d+)"
But generally it's better to use some kind of Serialization and Deserialization api(
Jackson) for json structure. As you are mentioning complex json structure some kind of api use are more relevant.

Search query in mongodb using regular expression

im building a website, using nodejs, expressjs, mongodb, mongoose, body-parser and etc..
basically i've created a search function, where you can search for users and basically it works, but the problem is, it is case-sensitive, i want to search for the user using case-insensitive.
I have found a solution here in stack overflow and tried it on my mongo shell. this is the command
db.loginusers.find({
$or:
[
{"firstname": {$regex: /^PIa$/i}},
{"lastname": {$regex: /^NAtUrE$/i}}
]
})
this works on mongoshell. so when i try to put this on my JS file,
app.post("/searchresult", function(req, res){
var thename = req.body.thename;
LoginUser.find({
$or: [
{"firstname": {$regex: /^thename$/i}},
{"lastname": {$regex: /^thename$/i}}
]
}, function(err, searchedUser){
if(err){
console.log(err);
res.redirect("back");
} else {
res.render("searchprofile", {foundUser: searchedUser});
}
});
});
it is not working, eventhough i tried to put the correct case on the name it is not functioning..
my question is, do i need to do something before i use the regex on my JS file?
THank you!
Because thename is a variable, use the RegExp object constructor to create a regex instance off the variable that you can then use in your query as:
var rgx = new RegExp("^"+ thename +"$", "i");
LoginUser.find({
"$or": [
{"firstname": rgx },
{"lastname": rgx }
]
}, callback);
can try it with $options:'i"
LoginUser.find({
$or: [
{'firstname': {$options:'i', $regex: 'PIa'}},
{'lastname': {$options:'i', $regex: 'NAtUrE'}}
]
})
or:
LoginUser.find({
$or: [
{'firstname': {$regex: /PIa/i}},
{'lastname': {$regex: /NAtUrE/i}}
]
})
also read docs: https://docs.mongodb.com/manual/reference/operator/query/regex/
it has some nice features like: $nin, $options: 'six'

Mongodb use regex expressions on field value

I have this document collection:
{
_id: 3,
version: "v1_8_R2"
},
{
_id: 2,
version: "v1_8"
}
{
_id: 1,
version: "v1_8_R3"
}
Using db.coll.find({version:"v1_8_R3"}) I get the id: 1 document, but id: 2 is compatible with the v1_8_R3 version and the id: 1 is outdated, and I don't want v1_8_R2 to be matched since it's incompatible with v1_8_R3
With regex I could solve that, but mongo doesn't allow to use it in fields unlike mysql
This works, but the other way around: db.coll.find(version: {$regex: "v1_8_R3", $options: "i"})
I would need something like this: db.coll.find({$regex: version, $options: "i"}: "v1_8_R3")
Then it would match v1_8, and wouldn't match v1_8_R2

Node.js and Mongoose regex query on multiple fields

I would like to query multiple fields using the same regular expression for both. In this query, I would like to accept a single text input and check both the firstName and lastName fields for results. I can query a single field just fine using the regex function in the mongoose documentation, but the syntax for an 'or' clause is giving me trouble.
var re = new RegExp(req.params.search, 'i');
app.User.find().or([{ 'firstName': { $regex: re }}, { 'lastName': { $regex: re }}]).sort('title', 1).exec(function(err, users) {
res.json(JSON.stringify(users));
});
(I'm running mongoose 2.7.1 on node.js 0.6.12)
The code above works fine for a query on multiple fields. Turns out I had some bad data.
My solution is to use $function that allows you to concatenate multiple fields and match their combined value against your regular expression.
const { search } = req.params;
var regex = new RegExp(`.*${search}.*`, 'i');
app.User.find({
$expr: {
$function: {
body: `function(firstName, lastName) { return (firstName+' '+lastName).match(${regex}) }`,
args: ['$firstName', '$lastName'],
lang: "js"
}
}
})
.exec((err, users) => {
res.json(JSON.stringify(users));
});