PanacheMongo find with wildcard - mongodb

I am trying to do a simple find in Panache but I'm stuck with the wildcard operator.
I have:
Model.find("payload.tags.name = ?1", "tag-to")
.stream()
.map(m -> (Model) m)
.collect(Collectors.toList());
and my document looks something like this:
{
...
payload:Object{
swagger:"2.0"
info:Object
host:"petstore.swagger.io"
basePath:"/v2"
tags:Array[
0:Object [
name:"tag-to-find"
description:"a tag i want to find"
]
]
}
}
When I try to find "tag-to-find" it works, but I don't know how to get the wildcards going. In mongoshell i just use db.Model.find({"payload.tags.name": /ag-to-/}) and it works.

What you are using in Mongo shell is a JavaScript regex.
You should also be able to use it with MongoDB with Panache.
You should normaly use the regex with the $regex operator, not sure how Mongo shell handle it but the following should work:
Model.list("payload.tags.name like ?1", "/tag-to/")
I use .list() instead of find() as it directly return the list of documents.
The query used here is what we called PanacheQL query that will maps to a MongoDB native query, you can also use a native query directly (with named or indexed parameters).
Simplified query is explained here: https://quarkus.io/guides/mongodb-panache#simplified-queries

Related

jessenger mongodb case insensitive query search

I have 1 issue with mongodb query search with exact values. i want to get collections irrespective of case sensitive. for this i found some querys like below. its working fine.
db.applications.find({"blocks.HOSPITAL_INFO.data.name": new RegExp('^VIKRAM$', 'i')});
in laravel i am using jessengers. . above query i can write as raw query in laravel.
but my issue is when ever i am using $In:{'a','b'} like this how can i write regex for this. FYI 'a','b' are dynamic array values. so how can i write regex for these array values?
The query in MongoDB would be something like this:
db.applications.find({"blocks.HOSPITAL_INFO.data.name":
{$in:[new RegExp('^a$', 'i'),new RegExp('^b$', 'i')]}});
OR, alternatively:
db.applications.find({"blocks.HOSPITAL_INFO.data.name":
{$in:[/^a$/i,/^b$/i]}});
...where a & b are your dynamic variables.
I'm not very familiar with Laravel, but I'm guessing it would look something like this:
$applications = Application::whereIn('blocks.HOSPITAL_INFO.data.name',
[new MongoRegex('^a$/i'), new MongoRegex('^b$/i')])->get();

Is there a findById shortcut for the MongoDB shell?

The most common thing I do in the mongo DB shell is find objects by ID, eg:
db.collection.find({_id: ObjectId("55a3e051dc75954f0f37c2f2"})
I do this over and over and I find having to wrap the id with ObjectId over and over gets old. I wish I had a findById-like shorthand form like what mongoose provides. I feel like the shell ought to be smart enough to figure out what I mean here for example:
db.collection.find("55a3e051dc75954f0f37c2f2")
How might I do this? Or are there any alternative ways of querying by id in the mongo shell?
Fortunately, you can extend the shell quite easily, for example by adding the following method to the ~/.mongorc.js file which is executed when you start the mongo client:
DBCollection.prototype.findById = function(id) {
return db.getCollection(this._shortName).find( { "_id" : ObjectId(id) } );
}
Then you can execute something like db.collection.findById("55a3e051dc75954f0f37c2f2")
The shorthand for find({_id: ObjectId("...")}) is find(ObjectId("...")).

Mongo find by regex: return only matching string

My application has the following stack:
Sinatra on Ruby -> MongoMapper -> MongoDB
The application puts several entries in the database. In order to crosslink to other pages, I've added some sort of syntax. e.g.:
Coffee is a black, caffeinated liquid made from beans. {Tea} is made from leaves. Both drinks are sometimes enjoyed with {milk}
In this example {Tea} will link to another DB entry about tea.
I'm trying to query my mongoDB about all 'linked terms'. Usually in ruby I would do something like this: /{([a-zA-Z0-9])+}/ where the () will return a matched string. In mongo however I get the whole record.
How can I get mongo to return me only the matched parts of the record I'm looking for. So for the example above it would return:
["Tea", "milk"]
I'm trying to avoid pulling the entire record into Ruby and processing them there
I don't know if I understand.
db.yourColl.aggregate([
{
$match:{"yourKey":{$regex:'[a-zA-Z0-9]', "$options" : "i"}}
},
{
$group:{
_id:null,
tot:{$push:"$yourKey"}
}
}])
If you don't want to have duplicate in totuse $addToSet
The way I solved this problem is using the string aggregation commands to extract the StartingIndexCP, ending indexCP and substrCP commands to extract the string I wanted. Since you could have multiple of these {} you need to have a projection to identify these CP indices in one shot and have another projection to extract the words you need. Hope this helps.

Mongoid search like with integer

I want use mongoid search like query with integer column.
I know use mongodb can use below command to query
db.test.find({ $where: "/^123.*/.test(this.example)" })
How write it with mongoid?
You know you can use all the usual MongoDB query operators with Mongoid's where so:
Test.where(:$where => '/^123/.test(this.example)')
If you look at the Mongoid::Criteria that that where gives you, you'll see something like this:
=> #<Mongoid::Criteria
selector: {"$where"=>"/^123/.test(this.example)"}
options: {}
class: Test
embedded: false>
and there's the underlying MongoDB query in selector.
BTW, that .* didn't do anything useful in your regex so I took it out.

Performing regex queries with PyMongo

I am trying to perform a regex query using PyMongo against a MongoDB server. The document structure is as follows
{
"files": [
"File 1",
"File 2",
"File 3",
"File 4"
],
"rootFolder": "/Location/Of/Files"
}
I want to get all the files that match the pattern *File. I tried doing this as such
db.collectionName.find({'files':'/^File/'})
Yet I get nothing back. Am I missing something, because according to the MongoDB docs this should be possible? If I perform the query in the Mongo console it works fine, does this mean the API doesn't support it or am I just using it incorrectly?
If you want to include regular expression options (such as ignore case), try this:
import re
regx = re.compile("^foo", re.IGNORECASE)
db.users.find_one({"files": regx})
Turns out regex searches are done a little differently in pymongo but is just as easy.
Regex is done as follows :
db.collectionname.find({'files':{'$regex':'^File'}})
This will match all documents that have a files property that has a item within that starts with File
To avoid the double compilation you can use the bson regex wrapper that comes with PyMongo:
>>> regx = bson.regex.Regex('^foo')
>>> db.users.find_one({"files": regx})
Regex just stores the string without trying to compile it, so find_one can then detect the argument as a 'Regex' type and form the appropriate Mongo query.
I feel this way is slightly more Pythonic than the other top answer, e.g.:
>>> db.collectionname.find({'files':{'$regex':'^File'}})
It's worth reading up on the bson Regex documentation if you plan to use regex queries because there are some caveats.
The solution of re doesn't use the index at all.
You should use commands like:
db.collectionname.find({'files':{'$regex':'^File'}})
( I cannot comment below their replies, so I reply here )