How can I search for collection data that contains a specific string within objects of an array using MongoDB?

In my MongoDB collection, I have multiple records. Each record contains an array with objects that have various fields.

Here is the structure of my collection:

[{
    "name" : "Karthik Thurairaja",
    "universities" : [ 
        {
            "name" : "Anna University",
            "city" : "Chennai"
        },
        {
            "name" : "Punjab University",
            "city" : "Chandigarh"
        },
        {
            "name" : "University of Delhi",
            "city" : "New Delhi"
        }
    ],
},
{
    "name" : "Sathish Kumar",
    "universities" : [ 
        {
            "name" : "Anna University",
            "city" : "Chennai"
        },
        {
            "name" : "University of Hyderabad",
            "city" : "Hyderabad"
        },
        {
            "name" : "University of Delhi",
            "city" : "New Delhi"
        }
    ],
}]

I want to retrieve all the records where the city of universities is equal to Chennai.

This is the query I attempted:

Collection.find({ "universities.city": "Chennai" }).exec(...);

Answer №1

To accomplish this, you can employ the $elemMatch query.

Collection.find({ universities: { $elemMatch: { city: "Chennai" } } }).exec(...);

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

There seems to be a malfunction in utilizing promises to manage flow

In an attempt to manage the sequential flow of execution in my code, I am encountering some issues. My goal is to read and update data from my database in the correct order. The function below is where I make calls to the database, with query functions wra ...

Tips for navigating libraries with Google CAJA

Is there a way to configure Google Caja to allow specific libraries to work without being sanitized? I have my own CAJA server and an application based on NodeJS. I'm providing users with code that is mostly related to charts and graphs, but certain ...

App that uses Angular 2 for real-time data refreshing

As a newcomer to Angular and Nodejs, I am venturing into the development of a MEAN stack cryptocurrency exchange application. My approach involves setting up a nodejs backend to retrieve the current exchange rate from an API and presenting it in the HTML. ...

Error in JSON format detected by Cloudinary in the live environment

For my upcoming project in Next.js, I have integrated a Cloudinary function to handle file uploads. Here is the code snippet: import { v2 as cloudinary, UploadApiResponse } from 'cloudinary' import dotenv from 'dotenv' dotenv.config() ...

Interact with socket.io and access variables with express-session

I am currently developing a chat feature for the customers of a website using express.js and socket.io. I am facing an issue in reading session values on the socket. Here is a snippet of my code. Any assistance would be greatly appreciated :) var express ...

What steps can be taken to resolve the issue of "Access Denied: Invalid token, incorrect code"?

Assigned to me recently for a school project is a coding challenge that consists of various parts. The final task involves uploading to a private GitHub repository and submitting a completion request through a POST request under specific conditions. I hav ...

Showing the information submitted through AngularJS on Node.js with the help of Express

When trying to pass data on the Angular side using a POST method, I encountered an issue. var data = { 'id': mydata.google_id, 'token': mydata.token, 'email': mydata.email, 'name': mydata.name }; $http.po ...

There was a problem encountered while attempting to open a PDF file generated by pdfkit in Node

const document = new PDFDocument(); // Add content to the PDF here const outputStream = fs.createWriteStream('output.pdf') document.pipe(outputStream); document.end(); The code above is creating a PDF file, but it's unable to be opened. An ...

How can I access the values of FormData on the server-side?

Is it possible to send FormData from the front end to the backend in order to manage its values? For example, consider the following code snippet: onFormSubmit = async (event) => { event.preventDefault(); const { imageFile, currentGroupId } = ...

Retrieve the request URL within the server.js file using Node.js

I am working on my server.js file where I define the server and all its settings. In order to properly set up my server, I need to determine the request URL before declaring those settings. This is important because the settings depend on the specific req ...

Encountering 500 Internal Server Errors when navigating certain routes using Next Js

Live Demo Upon deploying a Next JS project to Vercel, I encountered an issue where certain page paths like xxx.vercel.app/first or /second resulted in a "500: Internal Server Error". Strangely, these errors only occur on these specific routes. Despite no ...

Use Node.js with Selenium and WebdriverIO to simulate the ENTER keypress action on

I have put in a lot of effort trying to find the solution before resorting to asking this question, but unfortunately I have not been successful. All I need to know is how to send special characters (such as the enter key and backspace) with Node.js using ...

Having trouble getting my asynchronous promise to work properly

I am currently working on implementing a login server function and I am struggling to understand why the promise I'm making is not being called. My setup involves using MongoDB with Mongoose as the backend, which is connected to using User.findOne. A ...

Strategies for Effectively Managing Null Checks in Your JavaScript Project

When retrieving data from the BE API, it is in the format: { "details": { "address": { "street": "123/4", "city": "Banglore" } } } In our React project, we access this dat ...

Derbyjs installation failed: The system could not find a compatible version

Having some trouble installing derbyjs on my ubuntu machine. Here's what I've tried so far: sudo npm install -g derby Unfortunately, I'm running into the following errors: <200 response code here> npm ERR! error installing <a hre ...

Angularjs Socket.io Integration

I am working on implementing websockets in my Angular/nodejs application using socket.io. My main goal is to maintain a "live" array on the server of documents that are currently unavailable for editing (due to someone else already editing them). I starte ...

Python is seamlessly integrating with Redis, although there seems to be some compatibility issues with node

I successfully implemented the following Python3 code: import redis sentinel_host = '10.3.0.151' sentinel_port = 26379 sentinel = redis.Redis(host=sentinel_host, port=sentinel_port) masters = sentinel.sentinel_masters() for master_name, master ...

Navigating through an array of functions, some of which may return promises while others do not

Is there a way to efficiently iterate and execute an array of functions where some return promises, requiring the use of await, while most do not return promises, necessitating them to be set as async? for (let i = 0; i < this.steps.length; i++) { ...

Encountering an error when attempting to connect a nodejs REST API to an HTTPS URL using port 844

Attempting to initiate an API call from Node.js to a Tomcat server using the http/https module. There are two options for the API URL: - Functioning correctly and receiving a response var options = { host: 'samleapiurl.com', port: ...

How can I properly interpret a multipart form with arrays using Oak and Deno?

My current challenge lies in working with a form that contains both strings and arrays of data. Specifically, in Deno / Oak, I am struggling to retrieve the array of checked checkboxes when the form encoding is multipart. const body = await ctx.request.bod ...