Reputation: 7726
Does querying certain fields only save query time in mongodb query?
Assume I have a schema like shown below.
const CommentSchema = new mongoose.Schema({
commentText:{
type:String,
required: true
},
arrayOfReplies: [{
replyText:{
type:String,
required: true
},
likes: [{
objectIdOfUser: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true,
},
}],
}],
});
I am trying to find out if mongodb queries the whole document then filters it or if the filtering happens inside of mongodb.
If I have a large arrayOfReplies
array, for example 500,000 replies. Will the query below, as shown the mongoose docs, save query time as compared to querying the whole document?
Comment.findById(id, 'commentText', function (err, comment) {});
EDIT
I had earlier asked with this(see below). I have changed my question to reflect what I really meant to ask. Although the answer for the question with the query below is still there.
Comment.findById(id, 'replyText', function (err, comment) {});
Upvotes: 2
Views: 175
Reputation: 28356
Projecting only the fields you need can impact performance in some situation.
If the projection allows the query to be fully covered, there can be a significant improvement due to not needing to load documents at all. You can run you query with explain
to see if a fetch
stage was needed.
The mongod will fetch the entire document from disk into cache, and then copy the required data from the cache into the response.
If the query is returning a large number of documents, reducing the amount of data returned per document will reduce time required to send it on the network, and will permit more documents to fit in a single response batch which reduces the network overhead.
In the example of your query finding a single comment and getting the array of replyText you might see some negligible gains from reducing the amount of data sent over the network by not including the likes. (This is assuming that you don't actually index replyText)
Upvotes: 2