Explore with a pipeline using an array of IDs

I attempted to create a lookup function that processes an array containing object ids and timestamps of object y. While it worked smoothly using localfield and foreignfield, I encountered difficulties replicating the same outcome with pipeline.

(I used names like y for simplicity)

Successful version:

$lookup: {
   from: 'y',
   localField: 'ys.object_id',
   foreignField: '_id',
   as: 'docs',
},

The structure of objects in the ys array is as follows:

{
  object_id: ObjectID(),
  timestamp: Date(),
}

I aim to rewrite this expression to incorporate a pipeline, as I want to filter out some objects based on their timestamp attribute during the lookup process.

My attempt so far:

$lookup: {
   from: 'y',
   let: { ys: '$ys' },
   pipeline: [
     {
       $match: { $expr: { $eq: ['$_id', '$$ys.object_id'] } },
     },
   ],
   as: 'docs',
},

Database size: 20.4GB

Complete Query:

const query = [
  {
    $match: { 'ys.timestamp': { $lte: date, $gt: previousMonth } },  
  },
  {
    $limit: 100,
  },
  {
    $lookup: {
      from: 'y',
      let: { ys: '$ys' },
      pipeline: [
        {
          $match: { $expr: { $in: ['$_id', '$$ys.object_id'] } },
        },
        {
          $sort: { timestamp: -1 },
        },
        {
          $limit: 1,
        },
      ],
      as: 'doc',
    },
  },
];

Unfortunately, the above solution does not seem to work properly; it gets stuck and fails to return any results (times out eventually).

Is there a correct way to convert the successful approach into one utilizing a pipeline?

IMPORTANT: I modified the query to target a specific element by ID before executing the lookup. While this method did succeed, it took around 20 seconds to complete. I suspect this delay is causing the timeout in my usual query. Can someone explain the performance disparity between the two methods and suggest a workaround?

Answer №1

Almost there - consider implementing $in instead of $eq:

$lookup: {
   from: 'y',
   let: { ys: '$ys' },
   pipeline: [
     {
       $match: { $expr: { $in: ['$_id', '$$ys.object_id'] } },
     },
   ],
   as: 'docs',
},

Using $eq would search for a value exactly equal to the array, while utilizing $in searches for a value contained within the array (similar to includes).

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

New feature incorporated at the end of choices in MUI auto-suggest widget

Currently, I'm working on enhancing a category adder feature. Previously, I had limited the display of the "add category chip" to only appear for the no-options render scenario. However, I came across an issue where if there was a category like "softw ...

Define an array containing both primary and secondary categories

Incorporating PHP and MySQL. I manage a table (category) that comprises only three fields: id, name, parent. The field parent is set to 0 for the root category and an integer if it stems from another category. There can be multiple levels within this st ...

Guide on triggering a Bootstrap dropdown using an external button click

I have scoured almost half of the Internet, but I can't seem to find a clear example on how to accomplish this task. There are plenty of "solutions" out there, but nothing has been successful so far. Here is what I have attempted: $('#openner&a ...

What is the process for receiving notifications from Stack Overflow for new questions?

Interested in responding to the latest questions on JavaScript, React, React Native and Node.js. How can I stay updated on new user queries related to these topics? ...

Remove elements by specific value in JQuery, not by index position

I am looking to remove certain elements from the instances list, specifically those set to "three" or "five". The index of these elements can vary: { "address": "localhost", "name&lqt;"local"", "vars": { "instances" ...

Using a semicolon at the end of the line is considered a favorable practice when writing ES6 code in Babel

After browsing through various tutorials on the internet that utilize redux and react, I came across a common trend of omitting semicolons in ES6 code when using Babel. For instance, some examples neglect to include semicolons at the end of import or expo ...

Concealing a child component when hovering over its parent element with styled-components

I have a react component structured like this - const MyComponent = () => ( <ContainerSection> <DeleteButtonContainer> <Button theme="plain" autoWidth onClick={() = ...

Showcasing an HTML table using Material-UI

Currently, I have a list of issues being displayed in my browser using the material-ui code below: <Paper className={classes.root} elevation={4}> <Typography type="title" className={classes.title}> All Issues </Typography> ...

Examining Resolver Functionality within NestJS

Today I am diving into the world of writing tests for NestJs resolvers. I have already written tests for my services, but now it's time to tackle testing resolvers. However, I realized that there is a lack of documentation on testing resolvers in the ...

Encountering a issue while swapping the base address of a 2D array with a third variable

It appears that the objective of the programs is to switch the addresses stored in names[3] and names[40] using an auxiliary variable t, but I keep encountering an error. #include<conio.h> #include<stdio.h> int main() { char names[5][20] = ...

Is it possible to create a "text carousel" using HTML, CSS, and JavaScript?

Currently, I am in the process of building a 'text carousel' on my own, without seeking assistance. The progress so far can be viewed here (please stretch it out, as it is not responsive yet). Specifically, I am aiming to replicate the text carou ...

concealing the upper header while scrolling and shifting the primary header upwards

Is there a way to use CSS to move the main header navigation, including the logo and links, on my website up when scrolling down in order to hide the top black bar header that contains contact information? The website in question is atm.truenorthmediasol ...

I'm looking for a way to customize the featureLayer style specifically for level 1 administrative areas in React, using the react-google-maps/api library in conjunction with the

I am currently working on a project in Next.js where I am trying to customize the coloring up to administrative_area_level_1 boundaries on a Google Map using the react-google-maps/api library. However, my struggle lies in finding the correct method to add ...

What is the best way to integrate content from the tiptap text editor into a v-model?

Trying to directly bind this.newTutorial.content to editor.content, but no success so far. Console output: https://i.sstatic.net/BNRR4.png Code snippet: <style scoped> img.preview { width:200px; } .v-btn { height: 50px !important; min-wi ...

Unable to retrieve data from object properties despite their visibility

I am encountering issues accessing object properties, as they keep returning as undefined. I have attempted console.log(JSON.parse(this.$store.state.user.userId)); as well as console.log(JSON.parse(this.$store.state.user[0].userId)); However, when I ...

Sending information to a child component causes the parent's data to be modified as well

Transferring information from the parent to the child component has always been easy for me. However, I recently encountered an issue where updating the data in the child component also updates the data in the parent component simultaneously. Now, I am loo ...

Validating JSON arrays with RAML

My API RAML includes a query parameter called 'sfIds' that is of type array. I want to ensure that the elements within this array are always numeric, like [111, 222, 333] or [111]. Any non-numeric values in the array, such as [ABC,111], should no ...

Utilizing Numpy Arrays for Graph Representation

The data is currently in a specific format: tail head P01106 Q09472 P01106 Q13309 P62136 Q13616 P11831 P18146 P13569 P20823 P20823 P01100 ... Are there any suggestions for converting this data into a graph using a numpy array? I am interested in ca ...

Tips for efficiently waiting for the outcome in a unified function for multiple callbacks within node.js

Perhaps the question title is not the most appropriate, but let me explain what I am trying to achieve in my code // First Callback Function connection_db.query(get_measure_query,function(err,user_data1){ if(err){ // throw err; ...

Take action right away following a post in jQuery

I'm a beginner at using jQuery, and I have a question about displaying content immediately after making a post request. Currently, my code looks like this: $('#cur_select').on('change', function() { $.post( "getTable.php", { v ...