Mongoose Aggregate unionWith() API
Last Updated :
16 May, 2025
The Mongoose Aggregate unionWith()
API is a powerful method that allows you to combine the results of two collections into one. This is particularly useful when you want to merge data from different sources, ensuring more efficient and comprehensive data querying. unionWith()
lets you combine the results of a pipeline operation on two different collections, even if their structures differ slightly. It supports duplicate values and allows flexibility in data manipulation.
What is the Mongoose Aggregate unionWith()
API?
The Mongoose Aggregate unionWith()
method is part of the aggregation framework and allows you to combine documents from two collections into a single result set. Unlike other aggregation stages, unionWith()
enables you to include duplicate documents and merge two distinct collections based on a specific pipeline.
This method can be highly useful in scenarios where you're working with two collections that store related data, such as combining user data from different sources, or merging information about products and their reviews.
Syntax:
aggregate.unionWith( options )
- options: It accepts an object with two parameters, the collection name with which you want to perform the union operation and the pipeline array.
Parameters:
- coll: The name of the collection you want to perform the union operation with.
- pipeline: The aggregation pipeline array that defines the operation to apply to the second collection.
Return Value:
The unionWith()
method returns a combined result set in the form of an array. This result includes documents from both collections, and the order is not guaranteed.
Setting up Node.js application:
Step 1: Create a Node.js application using the following command:
npm init
Step 2: After creating the NodeJS application, Install the required module using the following command:
npm install mongoose
Project Structure: The project structure will look like this:Â
 Database Structure: The database structure will look like this, the following documents are present in the collection.
Â
Example 1: Merging Cricketer and IPL Player Data
In this example, we have established a database connection using mongoose and defined model over cricketerSchema, having three columns or fields "_id", "name", and "nationality". Another schema that we have defined is iplPlayerSchema, having four columns or fields "_id", "name", "teamName", and "nationality".
 At the end, we are using aggregate() method by selecting "nationality" and "_id" fields on Cricketer model and storing it into aggregate variable. On this aggregate variable, we are accessing unionWith() method, and in its parameters, we are sending another collection name to perform union operation and to get one combined result set.Â
Filename: app.js
JavaScript
// Require mongoose module
const mongoose = require("mongoose");
// Set Up the Database connection
mongoose.connect("mongodb://localhost:27017/geeksforgeeks", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const cricketerSchema = new mongoose.Schema({
_id: Number,
name: String,
nationality: String
});
const iplPlayerSchema = new mongoose.Schema({
_id: Number,
name: String,
teamName: String,
nationality: String
});
const Cricketer = mongoose.model('Cricketers', cricketerSchema);
const IplPlayer = mongoose.model('IplPlayers', iplPlayerSchema);
const aggregate = Cricketer.aggregate(
[{ $project: { nationality: 1, _id: 0 } }]
)
aggregate.unionWith({
coll: "iplplayers",
pipeline: [{ $project: { _id: 0, nationality: 1 } }]
}).then(result => {
console.log(result)
}).catch(err => {
console.log(err)
})
Step to run the program: To run the application execute the below command from the root directory of the project:
node app.js
Output:
[
{ nationality: 'India' },
{ nationality: 'Australia' },
{ nationality: 'England ' },
{ nationality: 'India' },
{ nationality: 'South Africa' },
{ nationality: 'Bangladesh' }
]
Explanations: In this output, you can see that the nationalities from both the Cricketers and IplPlayers collections have been successfully merged into a single result set.
Example 2: Combining All Fields from Both Collections
If you want to merge all fields from both collections, you don’t need to specify a pipeline for the second collection. The unionWith()
method will merge all documents from the two collections.
Filename: app.js
JavaScript
// Require mongoose module
const mongoose = require("mongoose");
// Set Up the Database connection
mongoose.connect("mongodb://localhost:27017/geeksforgeeks", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const cricketerSchema = new mongoose.Schema({
_id: Number,
name: String,
nationality: String
});
const iplPlayerSchema = new mongoose.Schema({
_id: Number,
name: String,
teamName: String,
nationality: String
});
const Cricketer = mongoose.model('Cricketers', cricketerSchema);
const IplPlayer = mongoose.model('IplPlayers', iplPlayerSchema);
const aggregate = Cricketer.aggregate()
aggregate.unionWith({ coll: "iplplayers" })
.exec((err, result) => {
if (err) {
console.log(err)
} else {
console.log(result)
}
})
Step to run the program: To run the application execute the below command from the root directory of the project:
node app.js
Output:
[
{
_id: 1, name: 'Virat Kohli',
nationality: 'India',
__v: 0
},
{
_id: 2,
name: 'David Warner',
nationality: 'Australia',
__v: 0
},
{
_id: 3,
name: 'Ben Stokes',
nationality: 'England ',
__v: 0
},
{
_id: 1,
name: 'Rohit Sharma',
teamName: 'Mumbai Indians',
nationality: 'India',
__v: 0
},
{
_id: 2,
name: 'David Miller',
teamName: 'Chennai Super Kings',
nationality: 'South Africa',
__v: 0
},
{
_id: 3,
name: 'Shakib Al Hasan',
teamName: 'Kolkata Knight Riders',
nationality: 'Bangladesh',
__v: 0
}
]
Explanations: In this example, all fields from both collections are successfully combined, showing data from Cricketers and IplPlayers.
Conclusion
The Mongoose Aggregate unionWith()
API is a versatile method that allows you to merge data from different collections with ease. By combining collections, you can gain deeper insights from your data and streamline your queries. Use this feature to join related datasets and perform more complex aggregation operations in MongoDB with Mongoose.
Similar Reads
Mongoose Aggregate prototype.unionWith() API The Mongoose Aggregate unionWith() API is a powerful method that allows you to combine the results of two collections into one. This is particularly useful when you want to merge data from different sources, ensuring more efficient and comprehensive data querying. unionWith() lets you combine the re
5 min read
Mongoose prototype.Aggregate() API The API.prototype.Aggregate() method of the Mongoose API is used to build aggregation pipelines. Aggregation is a method of processing many documents by sending them through multiple phases. Syntax:Â Model.aggregate() Parameters:Â pipeline: It is an array that is an aggregation pipeline as an array
3 min read
Mongoose Aggregate prototype.unwind() API The Aggregate API.prototype.unwind() method of the Mongoose API is used to perform aggregation tasks. It allows us to break down complex and nested array or document fields in the MongoDB database or Schema. It returns a document object for every element present in the field. It deconstructs the arr
4 min read
Mongoose Aggregate.prototype.then() API In Mongoose, the aggregate() method is a powerful tool used for performing aggregation tasks on MongoDB collections. It allows you to process and transform data in various ways. The then() method is used to handle the promise returned by the aggregate() method, enabling you to manage asynchronous op
4 min read
Mongoose Model.aggregate() API Mongoose, a popular ODM (Object Data Modeling) library for MongoDB and Node.js, provides an easy-to-use API for interacting with MongoDB databases. One of the most powerful features of Mongoose is the aggregate() method. In this article, we will expalin the aggregate() method, explain its syntax, us
4 min read
Mongoose Aggregate.prototype.exec() API Mongoose, a popular MongoDB ODM (Object Data Modeling) library for Node.js, provides a powerful API to perform advanced aggregation operations. One such method is Aggregate.prototype.exec(), which allows you to execute an aggregation pipeline and return a promise or use a callback to handle the resu
5 min read