Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB indexing for a Parse Server application

We have a social app where users can chat with each other and we’ve reached 350K messages!

We recently noticed that as the number of messages is growing, the find operations are getting slower! I believe the issue here is that the Message collection is not indexed.

That’s what I want to do now! I found this piece of code at the MongoDB docs:

db.comments.ensure_index(('discussion_id', 1))

This is my Message collection:

{
 chatRoom: <Pointer>,
 user: <Pointer>,
 text: <String>,
 isSeen: <Bool>
}

So I guess this is all I have to do:

db.Message.ensure_index(('chatRoom', 1))

Is that just it? Run this command and I’m all set? All existing and future messages will be indexed after that?

like image 470
Sotiris Kaniras Avatar asked Apr 21 '26 09:04

Sotiris Kaniras


1 Answers

Your index actually should depend on what your query looks like. Suppose your message query looks like this:

var query = new Parse.Query("Message");
query.equalTo("chatRoom", aChatRoom);
query.equalTo("user", someUser);
query.equalTo("isSeen", false);
query.descending("createdAt");
query.find().then(function(results){//whatever});

Then you would need to build an index on the Message collection specifically for this query. In this case:

db.Message.createIndex({_p_chatRoom:1, _p_user:1, isSeen: -1, _created_at: -1})

Alternatively, an index with just the chatroom will perform much better than no index at all

db.Message.createIndex({_p_chatRoom:1})

To really understand which indexes to build, you'll need to do some reading on the Mongo docs https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/#db.collection.createIndex

I personally use MLab for my Parse MongoDB, because I'm not very knowledgeable about databases, and they actually have a slow query analyzer that recommends indexes based on common queries in your application, so if you don't want to learn the finer points of MongoDB indexing, then MLab is a great place to start

like image 66
LulzCow Avatar answered Apr 24 '26 00:04

LulzCow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!