Searching for a specific key value in MongoDB by tag name within a complex, deeply nested document

 db.props.aggregate([{"$match":{release:"1"}},{"$project":{'_id':0, 'SHK.0':{"$filter":{"input":'$SHK.0.host',"as":'fil', "cond":{$in:['$$fil.Tags',"cd"]}}}}}])

The query above was utilized to extract specific data from the dataset shown below:

{ "_id" : ObjectId("5a0eafdf481fc70d171521b1"), 
    "release" : "1", 
    "product" : "1", 
    "project" : "1", 
    "patchset" : "1", 
    "common" : { 
        "active" : "YES", 
        "javahome" : "path" }, 
    "SHK" : [ 
        { 
        "host" : { 
            "value" : "demo", 
            "Tags" : [ "ci", "cd" ] }, 
        "appserver" : { 
                "value" : "demo", 
                "Tags" : [ "ci" ] }, 
        "appname" : { 
            "value" : "demo", 
            "Tags" : [ "cd" ] } } ] }

However, I encountered an issue where the desired results are not being obtained. The goal is to retrieve key-value pairs based on a specific tag name provided in the query - for instance, if 'cd' is specified, only values belonging to host and appname should be displayed as they contain the tag 'cd'. Thank you for any assistance.

Answer №1

If you are looking for a solution, here is one that might work for you:

db.props.aggregate([{
        "$match": {
            release: "1"
        }
    },
    {
        $unwind: '$SHK'
    },
    {
        "$project": {
            '_id': 0,
            'tag': {
                "$filter": {
                    "input": '$SHK.host.Tags',
                    "as": 'fil',
                    "cond": {
                        $in: ['$$fil', ["cd"]]
                    }
                }
            }
        }
    }
])

In order to achieve the desired result, remember to use the $unwind function on the initial array "SHK". Once you have flattened the "SHK" array, you can then focus on the "Tags" field. Make sure to correctly format the $in condition by enclosing it in square brackets. The correct syntax should look like this:

$in: ['$$fil', ["cd"]]

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

Map will be visible correctly only when the window is resized

I'm currently working on a project that utilizes a map engine from a private company which I am unable to disclose. The initial system was built in JQuery, but we recently underwent significant changes and now have it running on AngularJS. One side ...

Disabling the click functionality using ng-disabled on an anchor tag is effective, but the tag remains

I'm facing an issue with an anchor tag that I've styled as a download button using Bootstrap's CSS. The problem is even though I have the ng-disabled attribute in the tag, which visually disables the button, it can still be clicked. Here&apo ...

Issue encountered in React Native Expo: Attempting to access an object that is undefined while evaluating item.basicData.criminalName

const SearchContext = React.createContext(); class SearchProvider extends Component { state = { tfG: false, aboutToSearch: "criminals", }; render() { return ( <SearchContext.Provider value={{ state: t ...

Running React Boilerplate with forever is a great way to ensure your application stays

I plan on keeping the react-boilerplate application running indefinitely on the server. I recently came across forever, but I'm uncertain about how to pass parameters to it. The command to start the server looks like this: PORT=80 npm run start:produ ...

Using Vue.js and Laravel to compute hours and minutes

After receiving JSON data from a Laravel backend, I have time values such as "03:30:00", "01:45:00", and "00:15:00". Is there a simple method in Vue.js to add them together and display the result as "05:30:00"? ...

"Exploring the challenges of implementing a jquerytools tooltip with AJAX

Currently, I have set up an ajax call to run every 15 seconds. The issue arises when the ajax call disables the tooltip if it's open at that moment for a particular item. This results in the destruction of only the tooltip being displayed, leaving oth ...

unable to display preview images using the youtubev3 API

Currently in the process of creating a YouTube clone using the YouTube V3 API import React from 'react' import { Link } from 'react-router-dom'; import { Typography, Card, CardContent, CardMedia } from '@mui/material'; import{ ...

Getting a jquery lightbox up and running

After experimenting with three different jquery plugins in an attempt to create a lightbox that appears when clicking on a link containing an image, I am currently testing out this one: . Despite adding the plugin source in the head and ensuring that the l ...

A single feature designed to handle various elements

I currently have this HTML code repeated multiple times on my webpage: <form class="new_comment"> <input accept="image/png,image/gif,image/jpeg" id="file" class="file_comment" key=comment_id type="file" name="comment[media]"> <spa ...

MongoDB querying with multiple values greater than

My Node + Mongoose API is functioning well, but I am facing an issue while filtering data based on specific fields. How can I retrieve data such that: 1 < age < 3 AND 8 < age < 11 I have attempted the following: query.where('age').g ...

Develop a circular carousel using React JS from scratch, without relying on any third-party library

I am looking to replicate the carousel feature seen on this website. I want to mimic the same functionality without relying on any external libraries. I have found several resources explaining how to achieve this. Most suggest creating duplicate copies o ...

Ways to determine the length of a string that includes zero or negative width characters such as u0007 or 

Consider the following scenario: I have a string 'aa\b\u0007\u0007' var myString = 'aa\b\u0007\u0007'; console.log(myString); //=> 'a' (plus 2 beeps) console.log(myString.length); //=> 5 ...

Check if a specific number appears exactly once in an array and output either True or False

I am facing a challenge with comparing two arrays Array1 = [1,1,1,2,2,2,3,3] Array2 =[1,1,2,1] When comparing both arrays, the desired result is True if the number of occurrences of Integer 1 are the same. Array2 = [1,1,2] //Expecting False For the ab ...

Center the span in CSS by setting its position to absolute

I am trying to create a span element positioned as absolute inside a div. The div has top and left values set. When the user inputs text, the span expands with the given text towards the right to contain it. However, I would like it to grow symmetrically o ...

What is the process by which nodejs interprets and analyzes c++ code?

My expertise lies in Javascript, but I'm intrigued by the connection between Node.js and C++. Despite their differences, I wonder how they interact and communicate with each other. ...

The state of the checked value remains unaffected when using the Angular Material Checkbox

I am currently working on a list of elements and implementing a filter using pipes. The filter allows for multi-selection, so users can filter the list by more than one value at a time. To ensure that the filter persists even when the window is closed or t ...

Error in Three.js: "Framebuffer and active Texture causing a feedback loop" - Issue with Reflection Rendering

I am currently utilizing a CubeCamera along with WebGLCubeRenderTarget to capture the surrounding reflection in a manner similar to the example found at this link - https://threejs.org/examples/#webgl_materials_cubemap_dynamic However, I am encountering a ...

Tips to retrieve an Angular `value` from outside the module

customConfig.js angular.module("steam") .value("customConfig", { baseurl: "http://dev-back1.techgrind.asia/" }); To access the value outside the module, replace the " .." with customConfig.baseurl apiTest.js var frisby = require("frisby"); fris ...

React is informing that the `toggleNode` prop is not recognized on this particular DOM element

I have encountered the following warnings in my app, which I believe are causing it to not load all its features properly. Warning: React is indicating that the toggleNode prop is not recognized on a DOM element. If you intend for it to be a custom attrib ...

Creating a dynamic form with jQuery and assigning unique names to two different inputs

Currently, I am working on a program that necessitates adding a text box and textarea dynamically to a form. To achieve this, I am utilizing the clone function. Unfortunately, I have hit a roadblock in assigning unique IDs to each box. Below is the Jquery ...