---
title: "How to Query from Multiple MongoDB Databases"
description: "How to query from multiple MongoDB databases, clusters and even AWS S3 buckets at once using federated queries on MongoDB Atlas Data Lake."
url: https://www.joekarlsson.com/blog/how-to-query-from-multiple-mongodb-databases/
---

Mar 26, 2021 | 8 min read | [Web Dev](https://www.joekarlsson.com/blog/category/web-dev/) | [Written for MongoDB](https://www.joekarlsson.com/blog/written-for/mongodb/)

# How to Query from Multiple MongoDB Databases

**Blog** How to query from multiple MongoDB databases, clusters and even AWS S3 buckets at once using federated queries on MongoDB Atlas Data Lake.

Atlas Data Lake’s query feature is now called Atlas Data Federation, and MongoDB deprecated the separate Atlas Data Lake storage product in 2024. The federated queries below live under Data Federation today.

**TL;DR** I walk through setting up MongoDB Atlas Data Lake to run a single aggregation query across two separate databases hosted on different cloud providers. Federated queries make it feel like all your data lives in one place.

On this page

1.  [Prerequisites](https://www.joekarlsson.com/blog/how-to-query-from-multiple-mongodb-databases/#prerequisites)
2.  [Deploy a Data Lake](https://www.joekarlsson.com/blog/how-to-query-from-multiple-mongodb-databases/#deploy-a-data-lake)
3.  [Connect to Your Data Lake](https://www.joekarlsson.com/blog/how-to-query-from-multiple-mongodb-databases/#connect-to-your-data-lake)
4.  [Query from Multiple MongoDB Databases](https://www.joekarlsson.com/blog/how-to-query-from-multiple-mongodb-databases/#query-from-multiple-mongodb-databases)
5.  [Wrap-Up](https://www.joekarlsson.com/blog/how-to-query-from-multiple-mongodb-databases/#wrap-up)
6.  [Additional Resources](https://www.joekarlsson.com/blog/how-to-query-from-multiple-mongodb-databases/#additional-resources)
7.  [More Technical Posts](https://www.joekarlsson.com/blog/how-to-query-from-multiple-mongodb-databases/#more-technical-posts)

Have you ever needed to make queries across databases, clusters, data centers, or even mix it with data stored in an AWS S3 blob? You probably haven’t had to do all of these at once, but I’m guessing you’ve needed to do at least one of these at some point in your career. I’ll also bet that you didn’t know that this is possible (and easy) to do with MongoDB federated queries on a MongoDB Atlas Data Lake! These allow you to configure multiple remote MongoDB deployments, and enable federated queries across all the configured deployments.

![MongoDB Atlas Data Lake design graphic showing a lake with JSON brackets for waves and a sample data overlay.](https://www.joekarlsson.com/images/blog/how-to-query-from-multiple-mongodb-databases/atlas_data_lake_d52555700e-1-1024x682.webp)

In this post, I will guide you through the process of how to query from multiple MongoDB Databases.

**MongoDB Federated Query** allows you to perform queries across many MongoDB systems, including Clusters, Databases, and even AWS S3 buckets. Here’s how MongoDB federated query works in practice.

_Diagram: MongoDB Atlas Data Lake: a user sends a standard query to an application, which sends one federated query to the Data Lake compute plane. The compute plane spreads the work across MongoDB nodes in two clusters, three on AWS in US East and three on Google Cloud in US West, each running mongod with an agent._

**[1](https://www.joekarlsson.com/blog/how-to-query-from-multiple-mongodb-databases/#mn-w-1)** Nov 2021 Since MongoDB 5.1, $lookup can join sharded collections too. Both collections still have to be in the same database.

Note: In this post, we will be demoing how to query from two separate databases. However, if you want to query data from two separate [collections](https://docs.mongodb.com/manual/reference/glossary/#term-collection) that are in the same database, I would personally recommend that you use the [$lookup (aggregation pipeline)](https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/index.html) query. $lookup performs a left outer join to an unsharded collection [1](https://www.joekarlsson.com/blog/how-to-query-from-multiple-mongodb-databases/#mn-1) in the same database to filter documents from the “joined” collection for processing. In this scenario, using a data lake is not necessary.

**[1](https://www.joekarlsson.com/blog/how-to-query-from-multiple-mongodb-databases/#mn-w-1)** Nov 2021 Since MongoDB 5.1, $lookup can join sharded collections too. Both collections still have to be in the same database.

_tl;dr: In this post, I will guide you through the process of creating and connecting to a Data Lake in MongoDB Atlas, configuring paths to collections in two separate MongoDB databases stored in separate data centers, and querying data from both databases using only a single query._

## Prerequisites

In order to follow along this tutorial, you need to:

-   Create at least two [M10 clusters](https://docs.atlas.mongodb.com/cluster-tier/) in MongoDB Atlas. For this demo, I have created two databases deployed to separate Cloud Providers (AWS and GCP). [Click here for information on setting up a new MongoDB Atlas cluster](https://docs.atlas.mongodb.com/getting-started/).

![Screenshot of MongoDB Atlas Cluster overview page. There are red boxes highlighting that the two clusters used in this example are being hosted in two different cloud providers, AWS and GCP.](https://www.joekarlsson.com/images/blog/how-to-query-from-multiple-mongodb-databases/Screen_Shot_2022_10_08_at_12_25_05_PM_b8227181b8-1-1024x640.webp)

Screenshot of MongoDB Atlas Cluster overview page. There are red boxes highlighting that the two clusters used in this example are being hosted in two different cloud providers, AWS and GCP.

-   Ensure that each database has been seeded by [loading sample data into our Atlas cluster](https://docs.atlas.mongodb.com/sample-data/).
    
-   Have a [Mongo Shell](https://www.mongodb.com/docs/atlas/cli/v1.0/) installed.
    

## Deploy a Data Lake

**[2](https://www.joekarlsson.com/blog/how-to-query-from-multiple-mongodb-databases/#mn-w-2)** Jun 2022 MongoDB renamed Atlas Data Lake to Atlas Data Federation, so look for Data Federation in the Atlas menu.

First, make sure you are logged into [MongoDB Atlas](https://account.mongodb.com/account/login). Next, select the Data Lake option on the left-hand navigation [2](https://www.joekarlsson.com/blog/how-to-query-from-multiple-mongodb-databases/#mn-2).

**[2](https://www.joekarlsson.com/blog/how-to-query-from-multiple-mongodb-databases/#mn-w-2)** Jun 2022 MongoDB renamed Atlas Data Lake to Atlas Data Federation, so look for Data Federation in the Atlas menu.

![Screenshot from the MongoDB Atlas cluster overview page with a red box highlighting the Data Federation navigation button on the right side of the screen.](https://www.joekarlsson.com/images/blog/how-to-query-from-multiple-mongodb-databases/Screen_Shot_2022_10_08_at_12_36_31_PM_754a93fc69-1-1024x598.webp)

Create a Data Lake.

-   For your first Data Lake, click Create a Data Lake.
    
-   For your subsequent Data Lakes, click Configure a New Data Lake.
    

![Screenshot from the MongoDB Atlas Data Lake overview page with a red box highlighting the Create Data Lake button.](https://www.joekarlsson.com/images/blog/how-to-query-from-multiple-mongodb-databases/Screen_Shot_2022_10_08_at_12_40_12_PM_22d56d2b2b-1-1024x408.webp)

Click **Connect Data** on the Data Lake Configuration page, and select **MongoDB Atlas Cluster**. Select your first cluster, input `sample_airbnb` as the databases and `listingsAndReviews` as the collection. For this tutorial, we will be analyzing Airbnb rental data and some sample weather data to see if we can draw any insights into renting behaviors on Airbnb and the weather.

![Screenshot from the MongoDB Atlas Data Lake creation modal showing how I filled in the form for this demo.](https://www.joekarlsson.com/images/blog/how-to-query-from-multiple-mongodb-databases/Screen_Shot_2022_10_08_at_12_45_36_PM_8755ec364c-1-1024x640.webp)

Screenshot from the MongoDB Atlas Data Lake creation modal showing how I filled in the form for this demo.

Repeat the steps above to connect the data for your other cluster and data source.

Next, drag these new data stores into your data lake and click **save**. It should look like this.

![Screenshot from the MongoDB Atlas Data Lake overview page with a red box highlighting the data sources we created in the previous step and how I positioned them in the data federation.](https://www.joekarlsson.com/images/blog/how-to-query-from-multiple-mongodb-databases/Screen_Shot_2022_10_08_at_12_50_25_PM_3518d76180-1-1024x640.webp)

Screenshot from the MongoDB Atlas Data Lake overview page with a red box highlighting the data sources we created in the previous step and how I positioned them in the data federation.

## Connect to Your Data Lake

The next thing we are going to need to do after setting up our data lake is to connect to it so we can start running queries on all of our data. First, click connect in the second box on the data lake overview page.

![Screenshot from the MongoDB Atlas Data Lake overview page with a red box highlighting the "Connect" button.](https://www.joekarlsson.com/images/blog/how-to-query-from-multiple-mongodb-databases/Screen_Shot_2022_10_08_at_12_54_52_PM_17f9334325-1-1024x190.webp)

Click Add Your Current IP Address. Enter your IP address and an optional description, then click **Add IP Address**. In the **Create a MongoDB User** step of the dialog, enter a Username and a Password for your database user. (Note: You’ll use this username and password combination to access data on your cluster.)

## Query from Multiple MongoDB Databases

You can run your queries any way you feel comfortable. You can use MongoDB Compass, the MongoDB Shell, connect to an application or anything you see fit. For this demo, I’m going to be running my queries using [MongoDB Visual Studio Code plugin](https://marketplace.visualstudio.com/items?itemName=mongodb.mongodb-vscode) and using its [Playgrounds](https://docs.mongodb.com/mongodb-vscode/playgrounds/) feature. For more information on using this plugin, check out my post on [How To Use The MongoDB Visual Studio Code Plugin](https://www.joekarlsson.com/blog/how-to-use-the-mongodb-visual-studio-code-plugin/) Oct 20, 2020**How To Use The MongoDB Visual Studio Code Plugin** .

Make sure you are using the connection string for your data lake and not for your individual MongoDB databases. To get the connection string for your new data lake, click the connect button on the MongoDB Atlas Data Lake overview page. Then click on Connect using **MongoDB Compass**. Copy this connection string to your clipboard.

Note: You will need to add the password of the user that you authorized to access your data lake here.

![Screenshot from the MongoDB Atlas Data Federation connection modal with a red box highlighting your connection string that you will use to connect to your virtual database](https://www.joekarlsson.com/images/blog/how-to-query-from-multiple-mongodb-databases/Screen_Shot_2022_10_08_at_1_00_40_PM_f75ca08be1-1024x953.webp)

You’re going to paste this connection string into the MongoDB Visual Studio Code plugin when you add a new connection.

Note: If you need assistance with getting started with the MongoDB Visual Studio Code Plugin, be sure to check out my post, [How To Use The MongoDB Visual Studio Code Plugin](https://www.joekarlsson.com/blog/how-to-use-the-mongodb-visual-studio-code-plugin/) Oct 20, 2020**How To Use The MongoDB Visual Studio Code Plugin** , and the [official documentation](https://docs.mongodb.com/mongodb-vscode/).

**[3](https://www.joekarlsson.com/blog/how-to-query-from-multiple-mongodb-databases/#mn-w-3)**

[MongoDB Aggregation Pipeline Queries vs SQL Queries](https://www.joekarlsson.com/blog/mongodb-aggregation-pipeline-queries-vs-sql-queries/): If you think in SQL, I lined up common SQL queries next to their aggregation pipeline versions.

You can run operations using the MongoDB Query Language [3](https://www.joekarlsson.com/blog/how-to-query-from-multiple-mongodb-databases/#mn-3) (MQL) which includes most, but not all, standard server commands. To learn which MQL operations are supported, see the [MQL Support](https://docs.mongodb.com/datalake/supported-unsupported/mql-support/#std-label-data-lake-mql-support) documentation.

The following queries use the paths that you added to your Data Lake during [deployment](https://docs.mongodb.com/datalake/tutorial/deploy/#std-label-gst-deploy-adl).

For this query, I wanted to construct a unique aggregation that could only be used if both sample datasets were combined using federated query and MongoDB Atlas Data Lake. For this example, I am running a query to determine the number of theaters and restaurants in each zip code, by analyzing the `sample_restaurants.restaurants` and the `sample_mflix.theaters` datasets. If you haven’t added these data sources to your data lake, be sure to do that before moving forward with this query.

I want to make it clear that these data sources are still being stored in different MongoDB databases in completely different datacenters, but by using MongoDB Atlas Data Lake, we can query all of our databases at once as if all of our data is in a single collection! The following query is only possible using federated search! How cool is that?

```javascript
// MongoDB Playground

// Select the database to use. VirtualDatabase0 is the default name for a MongoDB Atlas Data Federation database. If you renamed your database, be sure to put in your virtual database name here.
use('VirtualDatabase0');

// We are connecting to `VirtualCollection0` since this is the default collection that MongoDB Atlas Data Federation calls your collection. If you renamed it, be sure to put in your virtual collection name here.
db.VirtualCollection0.aggregate([
	// In the first stage of our aggregation pipeline, we extract and normalize the dataset to only extract zip code data from our dataset.
	{
		$project: {
			restaurant_zipcode: '$address.zipcode',
			theater_zipcode: '$location.address.zipcode',
			zipcode: {
				$ifNull: ['$address.zipcode', '$location.address.zipcode'],
			},
		},
	},

	// In the second stage of our aggregation, we group the data based on the zip code it resides in. We also push each unique restaurant and theater into an array, so we can get a count of the number of each in the next stage.
	// We are calculating the `total` number of theaters and restaurants by using the aggregator function on $group. This sums all the documents that share a common zip code.
	{
		$group: {
			_id: '$zipcode',
			total: {
				$sum: 1,
			},
			theaters: {
				$push: '$theater_zipcode',
			},
			restaurants: {
				$push: '$restaurant_zipcode',
			},
		},
	},

	// In the third stage, we get the size or length of the `theaters` and `restaurants` array from the previous stage. This gives us our totals for each category.
	{
		$project: {
			zipcode: '$_id',
			total: '$total',
			total_theaters: {
				$size: '$theaters',
			},
			total_restaurants: {
				$size: '$restaurants',
			},
		},
	},

	// In our final stage, we sort our data in descending order so that the zip codes with the most number of restaurants and theaters are listed at the top.
	{
		$sort: {
			total: -1,
		},
	},
]);
```

This outputs the zip codes with the most theaters and restaurants.

```json
[
	{
		"_id": "10003",
		"zipcode": "10003",
		"total": 688,
		"total_theaters": 2,
		"total_restaurants": 686
	},
	{
		"_id": "10019",
		"zipcode": "10019",
		"total": 676,
		"total_theaters": 1,
		"total_restaurants": 675
	},
	{
		"_id": "10036",
		"zipcode": "10036",
		"total": 611,
		"total_theaters": 0,
		"total_restaurants": 611
	},
	{
		"_id": "10012",
		"zipcode": "10012",
		"total": 408,
		"total_theaters": 1,
		"total_restaurants": 407
	},
	{
		"_id": "11354",
		"zipcode": "11354",
		"total": 379,
		"total_theaters": 1,
		"total_restaurants": 378
	},
	{
		"_id": "10017",
		"zipcode": "10017",
		"total": 378,
		"total_theaters": 1,
		"total_restaurants": 377
	}
]
```

## Wrap-Up

**[4](https://www.joekarlsson.com/blog/how-to-query-from-multiple-mongodb-databases/#mn-w-4)**

[How to Manage MongoDB Data at Scale](https://www.joekarlsson.com/blog/how-to-manage-mongodb-data-at-scale/): Online Archive uses the same idea to move old documents to cheap object storage and still query them from one endpoint.

Congratulations! You just set up an Atlas Data Lake that contains databases being run by different cloud providers. Then, you queried both databases using the MongoDB Aggregation pipeline by using Atlas Data Lake and federated queries. This allows us to more easily run queries on data that is stored in multiple MongoDB database deployments across clusters, data centers, and even in different formats, including S3 blob storage [4](https://www.joekarlsson.com/blog/how-to-query-from-multiple-mongodb-databases/#mn-4).

![Screenshot from the MongoDB Atlas Data Federation overview page showing the information for our new virtual database.](https://www.joekarlsson.com/images/blog/how-to-query-from-multiple-mongodb-databases/Screen_Shot_2022_10_08_at_1_17_18_PM_0d104d8cc5-1-1024x284.webp)

> If you have questions, please head to our [developer community website](https://community.mongodb.com/) where the MongoDB engineers and the MongoDB community will help you build your next big idea with MongoDB.

## Additional Resources

-   [Getting Started with MongoDB Atlas Data Lake \[Docs\]](https://docs.mongodb.com/datalake/tutorial/getting-started/)
    

## More Technical Posts

-   [How to use MongoDB Client-Side Field Level Encryption (CSFLE) with Node.js](https://www.joekarlsson.com/blog/how-to-use-mongodb-client-side-field-level-encryption-csfle-with-node-js/) Jan 6, 2021**How to use MongoDB Client-Side Field Level Encryption (CSFLE) with Node.js**
-   [MongoDB Aggregation Pipeline Queries vs SQL Queries](https://www.joekarlsson.com/blog/mongodb-aggregation-pipeline-queries-vs-sql-queries/) Jan 25, 2021**MongoDB Aggregation Pipeline Queries vs SQL Queries**
-   [An Introduction to IoT (Internet of Toilets)](https://www.joekarlsson.com/talks/an-introduction-to-iot-internet-of-toilets/)
-   [How To Use The MongoDB Visual Studio Code Plugin](https://www.joekarlsson.com/blog/how-to-use-the-mongodb-visual-studio-code-plugin/) Oct 20, 2020**How To Use The MongoDB Visual Studio Code Plugin**
-   [Linked Lists and MongoDB: A Gentle Introduction](https://www.joekarlsson.com/blog/linked-lists-and-mongodb-a-gentle-introduction/) Sep 30, 2020**Linked Lists and MongoDB: A Gentle Introduction**

## Works on My Machine

Get the next post by email. My newsletter covers homelab builds, AI tools and open source, and it goes out when I have something to say.

It’s free, and you can unsubscribe anytime. You’ll get an email to confirm first.

![Joe Karlsson at his desk, chin on hand, with a microphone in front of him](https://www.joekarlsson.com/images/about/collage/studio.webp)

Joe Karlsson

Technology is better when it's weird and it's yours. Everything I write about runs in my house.

[More about me →](https://www.joekarlsson.com/about/)

[Bluesky](https://bsky.app/profile/joekarlsson.com) | [LinkedIn](https://www.linkedin.com/in/joekarlsson/) | [GitHub](https://github.com/JoeKarlsson)
