Encountering a problem with a multi-condition query in MongoDB using Golang

I have a record structured like this -

{ 
    "_id" : "580eef0e4dcc220df897a9cb", 
    "brandId" : 15, 
    "category" : "air_conditioner", 
    "properties" : [
        {
            "propertyName" : "A123", 
            "propertyValue" : "A123 678"
        }, 
        {
            "propertyName" : "B123", 
            "propertyValue" : "B123 678"
        }, 
        {
            "propertyName" : "C123", 
            "propertyValue" : "C123 678"
        }
    ]
}

When using my API to search, I would typically send an array similar to properties in the body of my POST request -

{ 
    "brandId" : 15, 
    "category" : "air_conditioner", 
    "properties" : [
        {
            "propertyName" : "A123", 
            "propertyValue" : "A123 678"
        }, 
        {
            "propertyName" : "B123", 
            "propertyValue" : "B123 678"
        }, 
        {
            "propertyName" : "C123", 
            "propertyValue" : "C123 678"
        }
    ]
}

To handle this data on my end, I've set up a structure for decoding it -

type Properties struct {
    PropertyName  string `json:"propertyName" bson:"propertyName"`
    PropertyValue string `json:"propertyValue" bson:"propertyValue"`
}

type ReqInfo struct {
    BrandID      int             `json:"brandId" bson:"brandId"`
    Category     string          `json:"category" bson:"category"`
    Properties   []Properties    `json:"properties" bson:"properties"`
}

I also want to execute a mongodb $and operation on the various properties, and only return documents that match all criteria. My issue lies in the fact that the number of elements within the properties array can vary. I need to be able to query with just

{ 
    "brandId" : 15, 
    "category" : "air_conditioner", 
    "properties" : [
        {
            "propertyName" : "A123", 
            "propertyValue" : "A123 678"
        }
    ]
}

and receive multiple matching documents (not just one).

I attempted to create a dynamically sized bson.M variable using a loop based on the size of the incoming properties array but struggled to find the correct approach!

What is the best way to tackle this problem?

Answer №1

To successfully accomplish this task, I created the $and section separately:

var AndConditions []map[string]interface{}
for i := 0; i < len(body.Attributes); i++ {
    log.Println(body.Attributes[i])
    currentCondition := bson.M{"attributes": bson.M{"$elemMatch": bson.M{"attributeName": body.Attributes[i].AttributeName, "attributeValue": body.Attributes[i].AttributeValue}}}
    AndConditions = append(AndConditions, currentCondition)
}

Subsequently, my query appeared as follows:

c.Find(bson.M{"brandId": body.BrandID, "category": body.Category, "$and": AndConditions})

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

Reconnecting the bone: A guide to reestablishing the mesh skeleton in Three.js after rebind

I am facing a challenge where I need to independently rotate bones on a rigged hand mesh along the global axis using direction vectors to calculate their orientation. To tackle this, I have developed the following code: function boneLookAtLocal(bone, posit ...

The use of the || operator within arguments

I am facing a challenge: //this console log displays correct value console.log('localstorage', localStorage.getItem('subMenu')); setSubMenu( JSON.parse(localStorage.getItem('subMenu') || JSON.stringify(s ...

The mongoose fails to establish a connection with the Mongo Db Atlas

I am having issues with my simple node express app when trying to connect to MongoDB atlas. Despite deleting node_modules and re-downloading all packages, I am still encountering the same error. The specific error message reads as follows: Cannot read pro ...

"Modifying state within a child component and utilizing the refreshed value in the parent component

I'm currently working on creating a simple header mini cart with a cart item counter in NextJS. I'm utilizing the form state value in the header component and then passing that value to the child components of the header where the numerical quant ...

What is the best method for implementing click functionality to elements that share a common class using only pure JavaScript

I am struggling to figure out how to select specific elements with the same classes using only pure JavaScript (no jQuery). For example: <div class="item"> <div class="divInside"></div> </div> <div class= ...

How to detect internet connection in any screen using React Native?

I'm facing confusion regarding how to display my customDialog when there is no Internet connection in my app. Currently, I have successfully shown my customDialog only in the LoginScreen. However, I want to display it from different screens, not just ...

Tips on refreshing the D3 SVG element following updates to the dataset state in a React application

Hey everyone, I'm currently experimenting with D3.js and React in an attempt to build a dynamic dancing bargraph. Can anyone provide guidance on how to reload the D3 svg after updating the dataset state within REACT? Feel free to check out my codepen ...

Encountering difficulties with a GraphQL structure within Apollo framework

I am currently in the process of building an Express server using Apollo 2. My schema is as follows: const typeDefs = gql `{ type Movie { id: ID! title: String year: String rating: String } type Query { ...

Create a function within jQuery that triggers when an option in a select field is chosen

As I edit a podcast, I have encountered a situation where an option is being selected through PHP code. Now, I am looking to implement jQuery functionality for when the option is selected from the select field. I have searched through various questions an ...

Executing a get request in Backbone without using the Option parameter by implementing the beforeSend method

After gathering insights from the responses to this and this queries, I have formulated the code below for a GET request: var setHeader = function (xhr) { xhr.setRequestHeader("Authorization", "Basic " + btoa($rootScope.login.Gebruikersnaam + ":" + $r ...

Determine whether a single array within an array of arrays is empty

I'm currently working on a Perl script that involves creating an array of arrays. This main array is meant to represent all the folders within the current directory, with each sub-array containing the names of files included in the respective folder. ...

What is the best way to organize a table with multiple state variables using nested loops?

What is the best way to display multiple variables in a table using a loop, such as i,j,k? this.state = { materials: ['m1', 'm2'], quantity: ['2', '4'], unitPrice : ['12&apo ...

Storing form data in a file using React

I am trying to create a feature in my react component where instead of submitting a form and sending the data, I want to write this data to a file for later use. Is it achievable using vanilla JS or should I consider using a library? This is how my handl ...

Node replication including a drop-down menu

Is there a way to clone a dropdown menu and text box with their values, then append them to the next line when clicking a button? Check out my HTML code snippet: <div class="container"> <div class="mynode"> <span class=& ...

JQuery animations not functioning as expected

I've been attempting to create a functionality where list items can scroll up and down upon clicking a link. Unfortunately, I haven't been able to achieve the desired outcome. UPDATE: Included a JSFiddle jQuery Code: $(document).ready(function ...

Prevent the Icon in Material UI from simultaneously changing

I'm working on a table where clicking one icon changes all icons in the list to a different icon. However, I want to prevent them from changing simultaneously. Any suggestions on how to tackle this issue? Code: import React from 'react'; im ...

Sending a bulky item as a straightforward argument or object

Here's a simple question - will the veryLargeObj pass as a reference in both scenarios? And if so, is there any performance difference aside from object creation? Example 1: import veryLargeObj from './here' function someFn(veryLargeObj){ ...

Guide on how to display registration form data on the current page as well as on a separate page

I am facing an issue with outputting registration form data to two different pages after successful validation. Specifically, I want the form data to be displayed on both the current page (form.php) and another page (profile.php). Despite my efforts to fin ...

When using navigator.mediaDevices.getUserMedia on an iPhone, the webcam is activated in fullscreen mode

I'm facing an issue with the webcam functionality on my app. It works perfectly on Android and Windows, but when I try to use it on iPhone, the webcam opens in a separate full-screen view. Any ideas on how to resolve this? Thank you for your help in a ...

Managing an unexpected variable when making an AJAX request

Here is a code snippet that I am working with: var User = { get: function (options) { var self = this; $.ajax({ url: options.url, success: function (data, response) { self.nextPageUrl = data.pagination.next_page; opt ...