Filter MongoDB Data from a list or an Array of ObjectIds
Getting the data set for a list of ObjectIds or an array of ObjectIds.
In this blog, you will learn how to fetch the data from the mongo DB for a List of ObjectIds or an Array of ObjectIds that has thousands of record in the DB.
Let's see when this function is needed,
let's assume that we have thousands of records stored in the MongoDB collection and we need to get only the records for specific ObjectsIds that we have.
(Ex- for validation of data, we need to get the specific records from the database, not all the data or one data record. but the data list filtered for the ObjectIds(or any other Ids or names) that we already have).
So to do that we need to use the functions that MongoDB has given us. For that, we can use Filter Definition. So here how we can use it.
Here is the example code that I have used in my project that I am working on right now to get the data as I said. and after that, I will explain what I have done here.
So what I have done is.
I am getting the values to the parameters to this repository layer method from the service layer.
As you can see I have assigned a parameter as “List<ObjectId> objectIds”. And I am getting the ID list that I need to get the records that I want.
To filter with a list we need to use the “FilterDefinitionBuilder<T>();”
As you see here, I have to use the model as the type because I need to give the filter criteria.
var filterDev = new FilterDefinitionBuilder<AttachmentSession>();
In the next line (7). I have told how this needs to be filtered with,
var filter = filterDev.In(_ => _.ID, objectIds);
and then we can get the data by calling the context and relevant method.
It will return only the relevant records by searching all Ids in the list that provided.
In this way, we can improve the performance of the application. because if we think to get the data for the ObjectId one by one at a time it will take times to do the process. but with this way, it will return all the relevant data at once and we can do the rest with the data that we got from the DB.
Also, you can use any other fields (Eg- name, Number, etc.) to filter data in this way.
Comment below if you have any other way to do the same.