Open In App

Mongoose Aggregate unionWith() API

Last Updated : 16 May, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

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