Atlas search contextual results filtering

Let me explain my objective with an example:

Let’s say I have a collection client_data where each document has a type property with a value of type1 or type2 or type3.

// "client_data" collection

{
	_id: ...
	type: "type1"
	...
}
{
	_id: ...
	type: "type2"
	...
}
{
	_id: ...
	type: "type3"
	...
}

// ... more docs

I also have a users collection that contains user objects.

// "users" collection

{
	_id: ...
	name: ""
	email: ""
	...

	permissions: [
		"type1", "type2", "type3"
	]
}

The permissions array that contains types that this user has access to.

Now if I want to run a search query on the client_data collection for this user, I’d have to ensure that I only return those documents which the user has access to based on their permissions.

Now, I could filter the results in the app layer, but that would not be efficient when client_data has a massive number of documents and these types of searches are very frequent - think autocomplete.

What I am looking for is a way to structure this at the level of search index and at the level of aggregation search query so that most of the heavy lifting is done by MongoDB.

Hello @Sid_J ,

Welcome to The MongoDB Community Forums! :wave:

I notice you haven’t had a response to this topic yet - were you able to find a solution?
If not, could you help me with below details?

As you mentioned autocomplete, do you specifically want to use $search?

If you are using MongoDB v6.0 in Atlas, you can specify the Atlas Search $search or $searchMeta stage in the $lookup pipeline to search collections on the Atlas cluster. The $search or the $searchMeta stage must be the first stage inside the $lookup pipeline. It helps in querying from different collections together.

Although this might help in your use-case but if you are doing this frequently then doing a $lookup for every single request might get expensive and might not be very performant so as an alternative you may be interested in checking out Materialised views which is a pre-computed aggregation pipeline result. On-demand materialized views are typically the results of a $merge or $out stage. It could provide a performance boost at the cost of extra storage space, and you will also need a way to trigger the data refresh so that the view remains up to date.

Also, what is the heavy lifting you are looking for? Is it raw speed, efficiency in terms of index usage? Could you please help me with this?

Regards,
Tarun

1 Like