Retrieve only ObjectIds that are embedded in an Array using MongoDB's .find() method

I am looking to extract only the ObjectIds from a specific document that is nested within the projects Array. I am working on creating a database where each user will have their own set of projects. Thank you!

db.users.find().pretty()
{
    "_id" : ObjectId("5762c0cf2b9a78006373a684"),
    "name" : "seq",
    "pass" : "seq",
    "projects" : [
        {
            "pid" : ObjectId("5762c0ba2b9a78006373a682"),
            "name" : "aaa"
        },
        {
            "pid" : ObjectId("5762c0ba2b9a78006373a683"),
            "name" : "bbb"
        }
    ]
}
{
    "_id" : ObjectId("5762c28d2b9a78006373a687"),
    "name" : "leq",
    "pass" : "leq",
    "projects" : [
        {
            "pid" : ObjectId("5762c2892b9a78006373a685"),
            "name" : "ccc"
        },
        {
            "pid" : ObjectId("5762c2892b9a78006373a686"),
            "name" : "ddd"
        }
    ]
}

Answer №1

Let's consider the scenario where we need to retrieve two PIDs.

{"pid" : ObjectId("5762c0ba2b9a78006373a682")} and {"pid" : ObjectId("5762c2892b9a78006373a686"),}

Specifically, we are interested in extracting inner documents only.

Therefore, the expected response should be as follows:

{
    "_id" : ObjectId("5762c0ba2b9a78006373a682"),
    "name" : "aaa"
},{
    "_id" : ObjectId("5762c2892b9a78006373a686"),
    "name" : "ddd"
}

The Aggregation framework has the ability to manipulate documents, filter only the necessary ones, and alter the internal structure during the project phase:

var match = {
    $match : {
        "projects.pid" : {
            $in : [ObjectId("5762c0ba2b9a78006373a682"), 
                   ObjectId("5762c2892b9a78006373a686")]
        }
    }
}
var unwind = {
    $unwind : "$projects"
};

// move the array object to the top level
var project = {
    $project : {
        _id : "$projects.pid",
        name : "$projects.name",
        // include other fields as needed
    }
}
db.vic.aggregate([match, unwind, match, project])

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

Submitting a nested JSON object in an AJAX request

When it comes to passing nested JSON through AJAX, the format of the sample request should be like this: { 'user': { 'email': email, 'password': password } } login(){ var email=document.getElementById(& ...

Tips for eliminating the menu bar in the external window generated by an Electron application's URL

Looking for a solution to remove the menu bar from a window that opens with an external URL in an Electron application? Check out the code snippet below: windowObject.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrows ...

What is the best way to propagate a react component's props to options following an apollo-client mutation?

How can you effectively pass a react component's props to options after performing a mutation using apollo-client? I am currently utilizing react in conjunction with apollo-client. Within a specific component, I am executing a delete mutation and the ...

Utilizing Vue to send information to the POST function

I am encountering an issue with passing data to the Vue.js post method. I am using vue-resource and according to the documentation, it should be structured like this: this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCall ...

In a multi-user environment, querying FaunaDB may not always retrieve the most up-to-date results

Background I've been delving into FaunaDB alongside React and managed to create some code with inspiration from this article. The project I'm working on involves a coffee poll/counter app - users are presented with various types of coffee and ca ...

Parsing JSON data on the client side in an ASP.NET application

I am currently working with JSON data that looks like this: "Table":[ { "AF":2000.00 "RegionNumber":1 "RegionName":"Black Sea" }, { "AF":100.00 "RegionNumber":1 "RegionName":"Black Sea" }, { "AF":15000.00 "RegionNumber":2 "RegionName":"Ista ...

What is the best way to transfer data from a parent component to a child component in ReactJs?

When dealing with nested react elements, how can you pass values from the parent element to a child element that is not directly inside the parent element? React.render( <MainLayout> <IndexDashboard /> </MainLayout>, document.b ...

Error Occurred: Angular View Not Loading

I created a new file named new.html to test navigation, but when I load the page View1.html should appear, instead I see a blank page. Below is the content of my new.html: <!DOCTYPE html> <html data-ng-app="demoApp"> <head> ...

What is the process for transforming a python list containing multiple 3D arrays into a single 3D array with a predefined shape?

I have a list called itemlist containing 25 3D Arrays, each with a shape of (128x128x3). My goal is to combine all these arrays into a single cohesive array, essentially creating an image. I anticipate the new shape to be (640, 640, 3), resulting in 5 row ...

Is there a way to synchronize the autohide duration for both the LinearProgress MUI and SnackBar components?

Can someone help me align my SnackBar with the LinearProgress so that they both have an auto-hide duration of 4 seconds? I've been struggling to figure it out for hours and haven't found a solution yet. Could the issue be in the useEffect part of ...

Angular 2: Enhancing User Experience with Pop-up Dialogs

Looking to implement a popup dialog that requests user input and returns the value. The popup component is included in the root component, positioned above the app's router outlet. Within the popup component, there is an open() method that toggles a ...

How to get an empty object as a response in a NODE.JS request?

For some reason, I am attempting to send an object to my backend. Even though I can retrieve valuable information from my network's payload, my req.body consistently returns an empty object. View my issue ...

Enhance your website with a dynamic div zoom feature using the Jquery Zoom

I've been scouring the internet for a jQuery plugin that allows me to zoom in on an image. There are many options out there, but I prefer ones that display the zoomed-in image in a separate area rather than directly on the original image. For example ...

Proper method of defining an action in Vuex

Do you think it's sufficient to create vuex-actions as simple as a1, without chaining then/catch calls? Or should I always go with creating Promises as in a2 (and also adding a reject branch)? Appreciate your insights... import Vue from 'vue& ...

What is the best way to send variables to a jQuery function?

I'm trying to create a form where I can hide unnecessary lines by toggling them with buttons using jQuery. I've managed to start working on a page, but I'm concerned about having to write a separate function for each button, which could beco ...

Using ng-bind-html does not offer protection against cross-site scripting vulnerabilities

I utilized ng-bind-html to safeguard against cross site scripting vulnerabilities. I came across information about sanitization and engaged in a discussion at one forum as well as another informative discussion. However, I encountered an issue where it di ...

Incorporate an HTML code string into an Angular 2 template

I am working with HTML code stored in a Component variable, shown below: import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: `Hi <div [innerHTML]="name"></div>`, styleUrls: [' ...

"Key challenges arise when attempting to execute the node app.js script through the terminal due to various middleware compatibility

I'm a beginner with node.js and I've encountered an issue while trying to run my node app.js file after incorporating a new file named projects.js which contains the following JS code: exports.viewProject = function(req, res){ res.render(" ...

I am interested in conducting a search in MongoDB by narrowing down the results based on specific dates

I am looking to get the total number of names with a status other than "SENT" and I also want to be able to filter this count based on a start and end date. Currently, only the first part works, which filters by date using the "date" field. Apologies for ...

Using AngularJS and JavaScript, set the Submit button to be enabled only when the email input is valid and a value is selected in

I'm trying to create a form that includes an email input field and a drop-down list sourced from a database array. Initially, the submit button is disabled when the form loads. My goal is to figure out how to activate the submit button only when the ...