Read Preference In MongoDB - node.js

How we can set read preference for a particular query in MongoDB? Can anyone please share NodeJS example for MongoDB find and aggregate query with the use of read preference? We are using mongoose as an ODM.

Taken from here.
Possible options are:
ReadPreference.PRIMARY
ReadPreference.PRIMARY_PREFERRED
ReadPreference.SECONDARY
ReadPreference.SECONDARY_PREFERRED
ReadPreference.NEAREST
Sample code:
collection.find({}).setReadPreference(new ReadPreference(ReadPreference.SECONDARY_PREFERRED)).toArray(function(err, items) {
// Done reading from secondary if available
})

Related

Python cloudant query "_id" by regex

I am new to ibm cloudant and I am using the python API for cloudant for my web application.
Is there any way I can retrieve documents from my couch database hosted on IBM cloudant instance using regex on "_id"?
I've read the python-cloudant documentation but I couldn't find anything.
Please help.
Thank you.
If you consider the underlying API, you can use the $regex operator in Cloudant Query. However, it won't use an index, so performance will be pretty dire, as it will scan the whole database. If possible, try arrange your ids such that you can find the subset you need with a range query instead. Given a db that looks like so:
% curl https://skruger.cloudant.com/aaa/_all_docs
{"total_rows":4,"offset":0,"rows":[
{"id":"aaron","key":"aaron","value":{"rev":"1-..."}},
{"id":"adam","key":"adam","value":{"rev":"1-..."}},
{"id":"ben","key":"ben","value":{"rev":"1-..."}},
{"id":"charlie","key":"charlie","value":{"rev":"1-..."}}
]}
we can retrieve all docs with id starting with "a" only,
% curl 'https://skruger.cloudant.com/aaa/_all_docs?startkey="a"&endkey="b"'
{"total_rows":4,"offset":0,"rows":[
{"id":"aaron","key":"aaron","value":{"rev":"1-..."}},
{"id":"adam","key":"adam","value":{"rev":"1-..."}}
]}

Is there a way to access mongodb node.js driver functionality while still using mongoose for schema definition?

What I am really trying to do is to make indexes for filtering and string matching of documents based on their property values.
I know that mongodb has built in operators such as $text that are very helpful with this sort of functionality.
I'm not sure how to access these operators while using mongoose, or if there are any methods i need to use to access them.
I want to use mongoose to still define schema and models but need the functionality of native mongodb.
Is this possible?
Below are my views, Please add if I miss anything or if something needs to be modified or well-explained :
1. You will still be able to use mongoDB's native functionalities on using Mongoose models.
2. Mongoose is a kind of wrapper on top of native mongoDB-driver.
3. It would be very useful if you want to have schema based collections/data.
4. Additionally it would provide few more features than native mongoDB's driver. You might see few syntax differences between those two.
5. Few examples like `.findByIdAndUpdate()` & `.populate()` are mongoose specific, which has equivalent functionalities available in mongoDB driver/mongoDB as well.
6. In general it's quiet common to define mongoose models and use those over mongoDB's functionality in coding(As in node.js - You would write all of your same DB queries on Mongoose models, queries that you execute in DB).
Point 2 :
Mongoose is an object document modeling (ODM) layer that sits on top of Node's MongoDB driver. If your coming from SQL, it's similar to an ORM for a relational database.
Point 3 :
In code if you're using mongoose models to implement your write queries, unless you define a field in model - it wouldn't be added to DB though you pass it in request. Additionally you can do multiple things like making a field unique/required etc.. it's kind of making your mongoDB data look like schema based. If your collections data is more like random data(newsfeed kind of thing where fields are not same for each document & you can't predict data) then you might not care of using mongoose.
Point 6 :
Let's say you use mongo shell or a client like mongo compass/robo3T and execute a query that's like this :
db.getCollection('yourCollection').find(
{
$text: {
$search: 'employeeName',
$diacriticSensitive: false
},
country: 'usa'
},
{
employee_id: 1,
name: 1
}
).sort({ score: { $meta: 'textScore' } });
you would do same on mongoose model(As yourCollectionModel is already defined) :
yourCollectionModel.find(
{
$text: {
$search: 'employeeName',
$diacriticSensitive: false
},
country: 'usa'
},
{
employee_id: 1,
name: 1
}
).sort({ score: { $meta: 'textScore' } });
You would see key functionality difference more on writes rather than reads while using mongoose, though all the above is not about performance - If you ask me, I can say you might see much performance gains using mongoose.
Ref : Mongoose Vs MongoDB Driver

How do I know which fields are indexed in pouchdb if I use query() API?

I am new to pouchdb and I am reading below source code:
db.query('product_index', {
startkey: ["01234"],
endkey: ["01234", {}],
include_docs: false
});
this code executes for a long time. After read some pouchdb document it looks like it builds index on the database when it run the first time. But I don't understand which fields are indexed based on above code.
Below code I can see it builds index on field foo. But how can I understand query API for building index? What is the different between using query and createIndex from index perceptive?
db.createIndex({
index: {
fields: ['foo']
}
})
Have you seen the PouchDB Guide Bulk operations section Please use 'allDocs()'. Seriously.?
Far too many developers overlook this valuable API, because they
misunderstand it. When a developer says "my PouchDB app is slow!", it
is usually because they are using the slow query() API when they
should be using the fast allDocs() API.
When designing your data structures it's very important to bear that in mind. You should define your record id fields to optimize data accessibility through allDocs().

Proper way to create indexes during deployment

I am creating an expressjs api and using mongodb. I have a decent understanding of indexes and I understand that they are expensive to create when there is data in the database.
In MS Sql Server you would create indexes when creating your database tables. My question is do I handle this creation of indexes in a post call in my express app or do I achieve this using scripts when deploymening my application?
For example I need Geospatial indexing.
Would index creation be handled in the express app like this?
//express post call
let col = db.collection( 'collection' );
col.createIndex( // someIndex );
col.insertOne( //Some document );
I am looking for the best method to creating the 'initial' state of my mongodb and specifically creating indexes I will need for certain collections before these collections contain any documents.
So, It may happen, You have a lot of data in your database while deployment and you do not want your Indexing terrible. Here's what MongoDB can Help. You can do indexing in Background which will not prevent all read and write operations to the database while the index builds.A simple Command:
db.collection.createIndex( { a: 1 }, { background: true } )
Check the Manual For details.
https://docs.mongodb.org/manual/tutorial/build-indexes-in-the-background/

How to query models by a property that is an array

I'm trying to do a 'findOne' operation in a model that has an array property and filter the results to only list the item if the string im searching is in that array.
Example:
var AppUser = server.loopback.getModel('AppUser');
AppUser.create({
"name":"juan"
"favoriteLetters":["a","b","c"]
},function(){
AppUser.findOne({where:{favoriteLetters:'a'}},function(error,appUser){
console.log(error,appUser);
});
});
So in this case i want to find a 'appUser' that has a favorite letter 'a'.
Thanks.
As far as I understood, possibility of such kind of a query depends on the underlying datasource and is not supported yet for relational DBs. But should be fine with memory storage or mongodb. More details and syntax for query is here: https://groups.google.com/d/msg/loopbackjs/8c8kw8EMiPU/yev3lsmrTFUJ
For anyone else who lands here, that query in your model is correct (for Mongo anyways).
{where:{favoriteLetters:'a'}
Reference:
Find document with array that contains a specific value

Resources