Open In App

Mongoose Aggregate prototype.unionWith() API

Last Updated : 05 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The Aggregate API.prototype.unionWith() method of the Mongoose API is used to perform aggregation tasks. It allows us to combine the pipeline result of two collections to get a single result set. It also allows duplicate values in the result set, however. the order is not specified.

Syntax:

aggregate.unionWith( options )

Parameters: This method accepts a single parameter as mentioned above and discussed below:

  • options: It accepts an object with two parameters, the collection name with which you want to perform the union operation and the pipeline array.

Return Value: This method returns a combined result set in the form of an array.

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: 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
    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' }   
]

Example 2: In this example, we are getting all the fields of both the collections in a single combined result set. To achieve this we just need to provide “coll” value to the unionWith() method.

Filename: app.js

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
    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
  }
]

Reference: https://mongoosejs.com/docs/api/aggregate.html#aggregate_Aggregate-unionWith



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads