mongodb querying logic mongoose and nodejs - node.js

I apologize beforehand if this is a repeat question but i could not find any and i am a beginner.
I am making a filter for documents of db.
lets say I want to query 8 fields of documents written in a object
filter={key1:{lowerlimit: 'value', upperlimit:'value'},
key2:{lowerlimit: 'value', upperlimit:'value'},
key3:{lowerlimit: '', upperlimit:'value'},
key4:{lowerlimit: 'value', upperlimit:''},
key5:[],
key6:['value','value'],
key7:['value','value','value'],
key8:['value']}
now how do i write the logic of query so that the fields whose value is not specified will not get query. if i query all the parameters as they are. no documents will be displayed because 'key5' is empty array and using $in on it will result in no documents.

You'd want to remove the key5 field from your query object when it's empty.
if (!filter.key5.length) {
delete filter.key5;
}

Related

How to query field exist some document in firebase

I using firebase, nodejs and i have a question how to query field exist some document.
Example :
Collections : users => document : A with field {
....
is_correct: true
}
document : B with field {
.....
}
In my above example , i have two document in collection users. On document A i have field is_correct: true and on document B field is_correct not exist.
My collection users about 15.000 document and it have 50 document contain field is_correct: true
When i write code look like :
await firestore.collection('users').where('is_correct', '==', true).get();
it can get correct me 50 document. But i don't understand it can using index on field is_correct or not ? And it can query best performance ? I understand firebase can't get document if field undefined. It impart in case ? Please help ? Thanks you
For a simple query like
firestore.collection('users').where('is_correct', '==', true)
you don't need to configure any index, Firestore does it automatically.
As you mentioned, only documents where the given field exists can match the query.
And this is the case also for Not-equal (!=) and not-in queries: they exclude documents where the given field does not exist, as explained in the documentation.
Also, note that a field exists when it's set to any value, including an empty string (""), null, and NaN (not a number).
So, in conclusion, if you want to query for documents where is_correct is not true, you need to create this field in these documents with a value different than true.

Mongodb how to aggregate more different fields of the same collection with the same request?

another shock with express and mongodb, I would like to aggregate more different fields of the same collection with the same request called aggregate4, together with another request called query (query is full text) (aggregate is regex) but I'm having difficulty, example:
collection.aggregate([{$match:{
$text: {$search: '\"' + query.split(' ').join('\" \"') + '\"'}, //full text req.query
name_lower: new RegExp('^'+ aggregate1), // req.query.aggregate1 ok
surname_lower: new RegExp('^'+ aggregate2),//req.query.aggregate2 ok
sex_lower: new RegExp( aggregate3),//req.query.aggregate3 ok
$or:[{
note4_lower: new RegExp(aggregate4), //problem //req.query.aggregate4
note5_lower: new RegExp(aggregate4),//problem //req.query.aggregate4
}]
}]).limit(myLimit)
.toArray(function.......
note that note4_lower and note5_lower share the same request (aggregate4), unfortunately I only receive the note4.lower column in this case or note5.lower reversing the or and.
I tried to do the same with two $OR one for note4_lower and one for note5.lower, I also tried with collection.find as well as aggregate but nothing, or I receive only the "COLUMN" note4.lower or only the "COLUMN" note5.lower ... In both columns there are NULL fields (so either the field has note4.lower or note5.lower)
can someone help me?
I hope I explained myself well, thanks!

Firebase Cloudfirestore update elements in a collections

i'm using firebase functions with nodejs and cloudfirestore to build an API, now i have a problem, i have a collection an inside the collection an array of objects.
My goal is to update only a specific element without read the whole object and then push it again.
This is how my "order's collection" looks like:
"someRestaurantId":[{id:1,desc:"test",val:3000},{id:2,desc:"test",val:4000},{id:4,desc:"test",val:5000}]
My goal es only update id 2.
This is what i been trying:
Get the full list based on
const document = db.collection('orders').doc(req.params.restId);
Iterate and find the correct element, modify it and update it again.
await document.update(fullobject)
The problem is that i need something more easy to handle since there could be thousand of element inside that array.
Looking at described issue, I think you should use subcollection (sometimes called nested collection) for that. However from the description it is hard to tell what do you have now.
Firestore collection structure is always like this:
collection -> document -> fields and nestedCollections
than nestedCollection has the same structure, so you can nest whole structure how many times you want, but always collection contain only documents and each document contain only fields and collection.
In presented collection description array is directly in the collection or directly in document which both are impossible.
Anyway my idea is to structure it following way:
Collection orders containing docs of various restIDs
every docs (ex. "someRestaurantId") contain subcollection with name ex. "RestOrders"
in the subcollection will add documents with ids like (1,2,3 etc.)
every doc in subcollection will have fields desc, val
Collection Orders:
Document RestID_1:
Subcolection RestOrders:
Document 1: {val: 3000, desc: test}
Document 2: {val: 3000, desc: test}
...
Document RestID_2:
Subcolection RestOrders:
Document 1: {val: 3000, desc: test}
Document 2: {val: 3000, desc: test}
...
And now to update value of "RestID_1", order "id 2" you can use:
db.collection('Orders')
.doc('RestID_1')
.collection('RestOrders')
.doc('2')
.update( {val: 4000} )
In above solution you avoid reading and updating big array. You can update only one filed of one document in nested sub-collection.

Find a document in a nested query mongodb

I have two collection A and B where in B there is a field that has the id of A as shown in the below. The code below returns nothing.
So I am trying to figure out if I want to use mongodb shell, how can I use the return cursor of A in order to point to ID values and send it to the value of AID key.
db.B.find({
'AID': db.A.find({'item': 'x'},
{'id': 1})
});

Node mongo bulk update, get the updated columns name

i have a bulk updation on mongodb in nodejs
i am facing the following scenario
user can update 20-30 fields at once, possibly he dont update all, he may change 1 or 2 or 5 or maybe all, i want to know exactly which are fields ie, whose value have be over-written with new values.
i need to know this because every field carry a weightage and if they update a particular field then i have to re-calculate the weightage of all the columns and assign it to the user
for example if
User.update({_id: user_id},{ $set : {key1:value,key2:value,key3:value... }})
now suppose key3 is over-written but key1 & key2 remains as it is,
so i want to know that key3 has been over-written.
how can i do that ?
if you use findOneAndUpdate function for updating, it's possible to retrieve document before updating, with that retrieved value you then can compare it with given document to find out witch fields has been updated.
The update function will be like this:
db.collection("Collection Name").findOneAndUpdate({"Find Query"},
{$set: {"Update Query"}},
{returnOriginal: true},
(err, res) => {
//... Some codes for comparing docs
});
The "returnOriginal" option makes the query to return updated document before update operation.

Resources