This question already has answers here:
How to query MongoDB with "like"
(45 answers)
Closed 8 months ago.
I worked with mongo before 3 years and now I'm back in Mongo and I don't know why today search ('%LIKE%' in SQL) is not working.
What I tried is as below.
{ "title": /${req.body.search}/i }
I searched a lot I all most tried all the way but don't know it seems not bed of roses for me.
Note: If I put static text then it's working but I need dynamic as per user search in my app.
Any help would be much appreciated.
MongoDB exposes as $regex operator to allow you search for items.
You could handle it like this:
// in your search handler
const searchTerm = new RegExp(req.body.search, "i")
Model.find({ "title": { $regex: searchTerm } })
Related
This question already has answers here:
Query Document Based on Regex in Firestore [duplicate]
(1 answer)
How to get a collection from firestore which is a Regular Expression?
(2 answers)
Closed 5 months ago.
I am trying with this code to search the product by name in the database but it gives those data which is the same as in a database. so give a better solution.
Code:
let response = await db
.collection("products")
.where("productName", ">=", req.body.searchText)
.where("productName", "<=", req.body.searchText + '\uf8ff')
.get();
Cloud Firestore doesn't provide a solution for full-text search. As you can see, you can use Elastic Search, Algolia or Typesense.
If you don't want such functionality, you can still use Firestore with a search that looks like this:
db.collection("products").orderBy("name")
.startAt(req.body.searchText)
.endAt(req.body.searchText + "\uf8ff");
If you're interested, for a better understanding, I recommend you read the following article:
How to filter Firestore data cheaper?
This question already has answers here:
How do I do a "NOT IN" query in Mongo?
(4 answers)
MongoDB not equal to
(6 answers)
Closed 2 years ago.
Need to remove items, ids of which are not presented in the array I pass. Don't want to make extra queries so I've already spent an hour trying to find something similiar to that but found nothing yet. I know MongoDB API is huge and has a ton of agregation operators but 'tis too complicated to me.
$nin
Syntax: { field: { $nin: [ <value1>, <value2> ... <valueN> ]} }
$nin selects the documents where:
the field value is not in the specified array or
the field does not exist.
This question already has answers here:
Mongoose: findOneAndUpdate doesn't return updated document
(16 answers)
Closed 3 years ago.
I am working on node js app using express.js and mongodb with mongoose module to handle the database.
in one case I need to update a user property languages using findOneAndUpdate method. this property is an array of objects should looks like [{"language":"Ar","level":4}]
when I update it using the following nodejs code :
User.findOneAndUpdate({_id:mongoose.Types.ObjectId(req.body.id)},
{$set:{[req.body.key]:req.body[req.body.key]}},(err,doc)=>{
console.log(req.body) // {id:5d1619fa7c11fa102210ef86,"languages":[{"language":"Ar","level":4}],key:"languages"}
if (!err) {
res.json(200,doc);
}else{
res.json(500,{error:err});
}
})
I get the following results
but when I try same thing from the mongo shell
db.users.findOneAndUpdate({"_id" : ObjectId("5d1619fa7c11fa102210ef86")},{ '$set': {"languages":[{"language":"Ar","level":4}]} })
I get the correct result
which is the correct expected results.
any idea why the nodejs snippet not working properly.
thanks in advance.
I think you are not getting the updated result back after update has successfully run. you need to pass new : true in your update query as the third argument.
By default mongodb returns the old document after the update, but you can specify to return the updated document in the query.
Try this :
User.findOneAndUpdate({_id:mongoose.Types.ObjectId(req.body.id)},
{$set:{[req.body.key]:req.body[req.body.key]},{new:true},(err,doc)=>{
...
//doc will be updated doc here
})
This question already has answers here:
How to Update Multiple Array Elements in mongodb
(16 answers)
Closed 4 years ago.
I've asked a question couple of days ago about updating arrays in nested arrays of objects. Right now MongoDB 3.6 officially supports it via arrayFilters feature.
Is it implemented in Mongoose 5.x.x? What's the syntax? Which method should I use?
Actually here is an example of findOneAndUpdate command:
Company.findOneAndUpdate(
{'companyId': parseInt(req.params.companyId)},
{$pull: {'companyDivisions.$[element].divisionDepartments': {'departmentId': parseInt(req.params.departmentId)}}},
{arrayFilters: [{'element.divisionId': parseInt(req.params.divisionId)}]},
(err) => {
if (err) res.status(400).json(err)
res.status(200).json({success: true, message: 'this worked without errors!'})
}
)
I had two problems:
1) I tried to add a test field which wasn't represented in my schema.
2) I completely forgot to parseInt the hell out of my params, because in my schema these are numbers.
Thank you everybody. :D
This question already has answers here:
MongoDB Regular Expression Search - Starts with using javascript driver and NodeJS
(2 answers)
Closed 9 years ago.
i am trying to do the equivaleny in mongodb to sql LIKE search, but i cant have the results that i expected, i am follow this mappig sql to monog, but the result json is always empty. if i use a literal string works , but when pass a variable nothing happens
app.get("/questions/search/:query", function(req,res){
var querySearch = req.params.query;
//res.send(querySearch)
Question.find({title: /querySearch/ },function(err,docs){
if(err) res.json(err)
res.json(docs)
});
})
That find command will search for documents where the title contains the string "querySearch". This doesn't seem to be what you want to do. When you want to use find with a regular expression created at runtime, pass a RegExp object.
But please note that searching with regular expressions is slow. When you don't need all the features of regular expressions and only search for whole words, a text index might be the better choice.