Working with MongoDB: Exploring ways to perform set operations on document collections

Can MongoDB perform the following query?

select id, title from posts
union all
select id, name from programs
sort by title asc;

I am looking to combine and sort documents from two different collections as one. Any assistance would be appreciated.

Additional Details

Specifically, I am conducting a text search across 2 collections and want to merge the results:

This is how my Express route handler is set up:

// Post and Program are Mongoose models
function (req, res) {
  const criteria = req.params.criteria

  Promise.all([
    Post
      .find({$text: {$search: criteria}}, { title: 1, score: { $meta: 'textScore' }})
      .sort({ score: { $meta: 'textScore' } })
      .exec(),

    Program
      .find({$text: {$search: criteria}}, { title: 1, score: { $meta: 'textScore' }})
      .sort({ score: { $meta: 'textScore' } })
      .exec()
  ])
    .then(results => reply([...results[0], ...results[1]]))
    .catch(err => handle(err))
}

While I can manipulate the results array using lodash, the challenge lies in displaying the results paginated, requiring fetching the necessary data per page on each request.

If I use lodash, it means fetching all data from the DB every time and then selecting the right page with lodash. It would be more efficient to fetch only what is required.

Hence, I hope for a solution like this:

Post
  .find({$text: {$search: criteria}}, { title: 1, score: { $meta: 'textScore' }})
  .unionAll(
    Program
      .find({$text: {$search: criteria}}, { title: 1, score: { $meta: 'textScore' }})
  )
  .sort({ score: { $meta: 'textScore' } })
  .limit(10)
  .exec()

Though it may seem like wishful thinking, is there a way to achieve these results directly from MongoDB, or do I need to rely on external libraries like lodash?

Answer №1

If you're looking to enhance your query, consider utilizing $facet and $lookup aggregation methods

db.collection.aggregate([
  { "$limit": 1 },
  { "$facet": {
    "c1": [
      { "$lookup": {
        "from": Post.collection.name,
        "pipeline": [
          { "$match": { "$text": { "$search": criteria }} },
          { "$project": { "title": 1 }}
        ],
        "as": "collection1"
      }}
    ],
    "c2": [
      { "$lookup": {
        "from": Program.collection.name,
        "pipeline": [
          { "$match": { "$text": { "$search": criteria }} },
          { "$project": { "name": 1 }}
        ],
        "as": "collection2"
      }}
    ]
  }},
  { "$project": {
    "data": {
      "$concatArrays": [ "$c1", "$c2" ]
    }
  }},
  { "$unwind": "$data" },
  { "$replaceRoot": { "newRoot": "$data" } }
])

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a dynamic header in a Bootstrap4 datatable with scroll search and pagination functionality

I've been attempting to create a Datatable using JSON Data with a dynamic header instead of a static one, but I haven't had much success. I want to display the table within a div element only, rather than using the traditional table tag, as it lo ...

Having difficulty setting up Keystone 6 with MongoDB

While setting up Keystone using MongoDB as the database, I encountered an error when running keystone-next. The error message displayed was: Error: Invalid db configuration. Please specify db.provider as either "sqlite" or "postgresql" at getDBProvider. T ...

The bootstrap table did not meet my expectations as I had hoped

I am currently using Bootstrap to create a basic two-column table similar to the one on the Bootstrap website here: http://getbootstrap.com/css/#tables. To achieve this, I have implemented a javascript function to display the table as shown below: $(&bso ...

Why is "undefined" being used to alert an ajax call response?

I am encountering an issue with a returned value from an AJAX request. The web method being referenced returns a boolean value of true or false. However, when attempting to access this value outside the AJAX method, I am receiving an "undefined" message :? ...

Showing and presenting Vue components using v-html

My database stores HTML content for my posts, like the example below. On the post page, I display the content using the following: <span v-html="content"></span> I'm curious about how I can make Vue Components work within HTML content fe ...

Is the each() method in jQuery essentially a for loop?

Experimenting with adding a serialized class to a group of objects, I attempted the following approach: jQuery('#preload img').each(function(){ jQuery('#thumbs').append('<img class="index' + index + '" src="&apos ...

When using Javascript in a JSP page, it may not always read every element within an array

A project I'm currently working on involves developing a web application that prompts users to input estimated costs for various items. To accomplish this task, I am utilizing a JavaScript function to generate the necessary fields dynamically. var fi ...

SailsJS and MongoDB not honoring unique attribute

I'm having trouble making the unique attribute work properly for checking and validating unique values when using Mongo in SailsJS. I keep ending up with identical usernames without any validation. Any suggestions or insights on how to fix this issue? ...

Enrolling JavaScript documents and connected inline programming

I need a solution for dealing with two arrays. The first array consists of URLs pointing to JavaScript files that I want to register using $.getScript(url); Next, the second array contains inline JavaScript commands that should be registered with $("html ...

Node.js Express JS is currently in the process of retrieving a file

I'm currently grappling with an issue while attempting to download a file using express js. Here is the function in question: var download = function(uri, filename, callback) { request .get(uri) .on('response', function (response) { ...

Modifying the value of a property in an object array created using the map method is ineffective

I have a collection of objects: https://i.sstatic.net/XNrcU.png Within the collection, I wished to include an additional property to the objects. To achieve this, I utilized the map function: returnArray = returnArray.map((obj) => { obj.active = "fal ...

Include a class in the html root tag

Is there a way to dynamically add a class to the root HTML tag when a specific button is clicked? Most resources I've found only show how to add classes to div elements with IDs. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http ...

What's causing the browser to repeatedly display a "cannot get" message?

I've been working on a project utilizing node js and express. Despite fixing some errors, I still encounter a "cannot get" error when executing the code in the browser. The terminal confirms that the Express server has started at port : 3000 and the M ...

How to format time in Node.js using PostgreSQL

I have set up two tables in my Postgres database, one called users and the other called card_info. I have implemented an endpoint for new user registration, and I have included a field named dateCreated in the code snippet below. Register.js const handle ...

Be patient for the complete loading of the image during an AJAX operation

My webpage includes an ajax action that loads a div containing an image on the left and text on the right. The issue I am facing is that the text loads first, aligned to the left, and then the image loads, causing the text to shift to the right, resulting ...

Remove the default selection when a different option is chosen using Bootstrap

I have implemented the Bootstrap-select plugin () for a multiple select dropdown on my website. Upon page load, there is a default option that is already selected. See image below: https://i.stack.imgur.com/SzUgy.jpg <select id="dataPicker" class=" ...

Tips for enhancing undo/redo functionality when working with canvas drawings in React

Currently, I am working on implementing undo/redo functionality for html-canvas drawing on medical (.nii) images in a React application. The images consist of slices stored in a Uint8ClampedArray and usually have dimensions around 500 (cols) x 500 (rows) x ...

Count will be zero in Mysql if there are no rows available

Currently, I am in the process of creating a query to count the number of entries within various categories and states. The rows in a table are currently grouped by category and state. Here is the current version of my query: SELECT CASE WHEN J.MI ...

View hyperlinks within a designated DIV container

I have a menu wrapped in a DIV element and I want to open the links from the menu in another DIV called TEST. So far, the only method I've found is using an iframe, but I'm looking for another solution, possibly with JavaScript (without using AJA ...

Is there a way to tally unique occurrences in consecutive seconds?

I have a database that includes columns for date, timestamp (HH:MM:SS), and phone numbers. My goal is to identify unique calls that occur in sequential seconds. For example: Date Timestamp Phone_number 10-12-2019 15:15:23 999-999-9999 ...