Exploring nested arrays of subdocuments in a query

UPDATE: It is advised not to use the special characters &" in the query. They are meant for updates only.

SOLUTION: Thanks to Gibbs

correct: 
const result : any = await mongoose.model('Events').update(
    {
        _id: eventId,
        "groups._id": groupId,
        "groups.users._id": userId
    },

incorrect:
const result: any = await mongoose.model('Events').findOne(
    {
        _id: eventId,
        "groups._id": "5f270416e7964b20d6f8953e",
        "groups.$.users": { _id: '5f270877b4942d2528885dbd' }
    })
    // OR:
    {
        _id: eventId,
        "groups._id": "5f270416e7964b20d6f8953e",
        "groups.$.users._id" : '5f270877b4942d2528885dbd',  
    })

When using only the first two conditions, (eventId and groups [$_id]), it returns the event correctly. However, adding the third condition causes issues.

Does anyone have an idea why this is returning null? The object IDs are directly retrieved from the database. Thank you!

{
    "_id": ObjectId("5f270416e7964b20d6f8953d"),
    "lastRounds": [],
    "name": "EpicFest",
    "start": 1596392488896.0,
    "end": 1596392500896.0,
    "groups": [
      {
        "_id": ObjectId("5f270416e7964b20d6f8953e"),
        "name": "Vossius",
        "users": [
          {
            "created": 1596393590778.0,
            "sessionId": null,
            "feedBack": {
              "messagesSent": 0,
              "messagesSentLiked": 0,
              "messagesReceived": 0,
              "messagesReceivedLiked": 0,
              "userFeedbackReceived": [],
              "chatFeedbackReceived": [],
              "_id": ObjectId("5f270877b4942d2528885dbe")
            },
            "_id": ObjectId("5f270877b4942d2528885dbd"),
            "image": "someAvatr",
            "name": "hans",
            "groupId": "5f270416e7964b20d6f8953e",
            "results": []
          },
          
        ]
      },
      {
        "_id": ObjectId("5f270416e7964b20d6f8953f"),
        "users": [],
        "name": "Ignatius"
      }
    ],
    "results": [],
    "theses": [],
    "rounds": 10,
    "schedule": [],
    "__v": 4
}

Answer №1

Utilize the aggregate pipeline to retrieve data based on the nested sub-document.

Start by filtering with the eventId in the initial match stage and use $elemMatch for the inner groupId. Then, unwind the group and groups.user.

After unwinding, you will have a flattened object structure to further filter and apply a match stage on groups.user._id.

const pipeline = [
    {
        $match: {
            _id: eventId,
            groups: {
                $elemMatch: mongoose.Types.ObjectId('5f270416e7964b20d6f8953e')
            }
        }
    },
    {
        $unwind: '$groups'
    },
    {
        $unwind: '$groups.users'
    },
    {
        $match: {
            '$groups.users._id': mongoose.Types.ObjectId('5f270877b4942d2528885dbd')
        }
    }
];
const result: any = await mongoose.model('Events').aggregate(pipeline).exec();

Answer №2

Database Play

db.collection.find({
  _id: ObjectId("5f270416e7964b20d6f8953d"),
  "teams._id": ObjectId("5f270416e7964b20d6f8953e"),
  "teams.members._id": ObjectId("5f270877b4942d2528885dbd")
})

You attempted to use a String

"5f270416e7964b20d6f8953e"
. Instead, it should be of type ObjectId

To access a nested element, you can utilize the . notation or $elemMatch

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

What could be the reason for the mongostat executable file being absent in MongoDB Enterprise version 4.4.0?

Attempting to execute the mongostat command. anish@Anishs-MacBook-Pro bin % mongostat --port 27017 zsh: command not found: mongostat The command is failing because the executable file is missing. Puzzled as to why the file is absent from the mongodb ente ...

Angular2 - error in long-stack-trace-zone.js at line 106: Zone variable is not defined

Currently, I am utilizing the Angular2 starter with webpackjs AMD. While there are no build errors showing up, I encounter some issues when browsing (using npm server), resulting in the following errors: What aspects might I be overlooking in my build con ...

The error message "Property 'pipe' is not found on 'ReadableStream<Uint8Array>'" indicates that the pipe method cannot be used on the given type

Within a function resembling Express.js in Next.js, I am working on fetching a CSV file with a URL that ends in .csv. Using the csv-parser library to stream the data without persisting the file and transform it into an array. Here is an excerpt of the code ...

Error message: The attempt to convert the value ":listId" to an ObjectId for the model "Task" failed at the path "_listId"

I am encountering the casterror in my mongoose. I apologize for raising this question again, but I am struggling to identify my error. While I can see the results using Postman, I am unable to display the tasks on my frontend. I am facing difficulty in fet ...

What is the best way to insert information into a complicated JSON dictionary using Python?

My task involves populating a JSON API Payload before sending it in the API request. The process includes working with 2 files: A text file containing JSON payload format, named json.txt A yml file containing actual data, named tdata.yml. I am developing ...

Experiencing difficulty in transferring data from a text file into an array of structures

At my current stage in university, I am enrolled in a beginner C programming course. Our final examination project revolves around a patients' database. My task is to extract data from a text file and store it in a struct array with a size of 10000. ...

Enhance the JSON output of API calls by incorporating a timestamp

Looking to improve my current JSON response by adding a timestamp in key-value format. Currently, here's what I have: now = datetime.datetime.now().isoformat(sep=" ", timespec="seconds") result = session.get(urljoin(baseurl, ...

Nestjs RabbitMq Microservices

I'm currently developing a microservice that is responsible for receiving messages from RabbitMQ. However, I am encountering an error message as follows: ERROR [Server] There is no matching event handler defined in the remote service. Event pattern: u ...

Failure of Apache POI to refresh data

I've been working on a piece of code designed to reformat data in an Excel spreadsheet. The process involves iterating through rows and cells, identifying specific keywords, and then extracting corresponding values from the 14th cell in each row. Howe ...

Inquiry About Binary Subarrays and their Sum

My interest was piqued by a challenge involving a binary array named nums, which could be a sequence like 10101, 00000, or any other combination of 0s and 1s. The task at hand was to develop a program that could determine the number of non-empty subarrays ...

Aggregating nested documents in MongoDB

I am in possession of a document that is structured in the following manner: "summary":{ "HUL":{ "hr_0":{ "ts":None, "Insights":{ "sentiments":{ "pos":37, "neg":3 ...

Tips on Importing a Javascript Module from an external javascript file into an <script> tag within an HTML file

I'm facing an issue while attempting to import the 'JSZip' module from an external node package called JSZip in my HTML File. The usual method of importing it directly using the import command is not working: <script> import ...

Contrast the differences between arrays and inserting data into specific index positions

In this scenario, I have two arrays structured as follows: arr1=[{room_no:1,bed_no:'1A'}, {room_no:1,bed_no:'1B'}, {room_no:2,bed_no:'2A'}, {room_no:3,bed_no:'3A'}, {room_no:3,bed_no:'3B ...

Assign the primeng dropdown's value to the model in a reactive form

I am currently encountering an issue while populating a form that contains several PrimeNg dropdowns. To simplify, let's consider an example similar to the ones provided on their website. <form [formGroup]="myFormGroup"> <p-dropdown [optio ...

Different results are being obtained when destructuring props in a component

Just diving into the world of React and trying to grasp destructuring. I've been doing some reading on it, but I'm currently stuck. When I try to destructure like this function MList({action}) { // const data = [action];}, I only get 'camera ...

How to properly import a new typings file in Typescript for Node.js applications?

I'm feeling quite overwhelmed by the different methods available for importing a Typings file. It seems like there are numerous ways to accomplish this task. Currently, I am working on a nodejs program. I successfully installed momentJS through typi ...

What is the alternative method for applying a CSS class in the click event in Angular 7 without relying on ng-Class or ng-Style?

Is there a way to dynamically add or remove CSS classes to HTML elements in Angular7 without relying on Ng-Style and Ng-Class directives? I'd like to achieve this functionality when clicking on the elements. Appreciate any insights you can provide. T ...

Learning about the functions Promise.all and Array.map()

My current project involves retrieving data from multiple APIs and aggregating them into a final array that will be displayed in the UI using React. Let me explain the scenario. First, I retrieve the main data from the primary API: const response = await ...

Using Angular to include more than two parameters in an HTTP GET request

Currently, I am developing an application that requires downloading a file upon clicking a button within a template. The screen displays multiple files, each with its own corresponding button. I need to send the index number of the array to Angular and pas ...

Steps for modifying the value of a field within an Angular formGroup

Is there a way to update the value of the "send_diagnostic_data" field in a separate function? private generateForm(): void { this.messageForm = new FormGroup({ message: new FormControl(''), date: new FormControl(new Date()), messag ...