Searching for fields in MongoDB using an AND clause to verify their existence

Within my collection, there are various documents that store information about individuals:

{
    name : 'Peter'
    city : 'New York'
    dogs_owned : 2,
    cats_owned : 1,
}
{
    name : 'Amir'
    city : 'Chicago'
}
{
    name : 'James'
    city : 'Chicago'
    dogs_owned : 3
}
{  
    name : 'Leilani'
    city : 'Chicago'
    cats_owned : 3,
}

I am looking to create a find query that will retrieve documents where either the "cats_owned" or "dogs_owned" field exists and another condition is satisfied.

Specifically, I want to fetch the documents that have either cats or dogs owned, combined with the condition that the city is Chicago.

Consequently, the query should return the records for James and Leilani in the example above. This operation will be carried out using the node driver for MongoDB.

Answer №1

Utilize the $or & $exists operators:

const MongoClient = require('mongodb').MongoClient;
const url = "your_db_or_cluster_url";

MongoClient.connect(url, function (err, db) {
    if (err) throw err;
    const dbo = db.db("your_db_name");
    dbo.collection("your_collection_name").find({
        city: "Chicago",
        $or: [{ dogs_owned: { $exists: true } },
        { cats_owned: { $exists: true } }]}, function (err, result) {
        if (err) throw err;
        console.log(result);
        db.close();
    });
});

Run a test here: mongoplayground

Important Note: Ensure to maintain appropriate indexes.

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

When yarn.lock is found, the installation of private npmjs packages will not succeed

My current project relies on specific packages that are hosted on a private npmjs account, like @myaccount/first-package. In my project's .npmrc file, I have the following settings: @myaccount:registry=https://registry.npmjs.org/ //registry.npmjs.org ...

Utilize the Expect --upload-file header in your curl request to interface with Node.js

Struggling with uploading a file to Autodesk using the View and Data API, I am having trouble figuring out how to send curl by http or request lib. Specifically, I'm unsure of how to set the expect header. Below is the curl command I have been trying ...

Setting the Content-Type of a JavaScript file within a NodeJS application

I am facing an issue with opening a js-file on my NodeJS server, as it always specifies the .js file with a Content-Type of "text/html." My objective is to send user-input from an html form to a JavaScript file for performing calculations and later genera ...

In what circumstances could my code encounter errors or failures?

Take a look at the code snippet below - exports.ticketList = function(req, res, next) { Ticket.find(function(err, data) { if (err) { //---- Error Handler ---- return next(err); } res.render('ticket ...

Unable to Perform Redirect Function on Express.js version 4

Hello everyone, I'm a newcomer to using Express 4 and I am currently working on implementing user authentication with passport-local. const UserModel = require('../models/Userinfo').Userinfo; const Security = require('security&apos ...

Error: The function SomeFunction is not recognized as a valid function (Mongoose library)

Help needed! I'm encountering an error stating "TypeError: User.getUserByUsername is not a function at Strategy._verify (.../routes/users.js:65:10) var User = require('../models/user'); passport.use(new LocalStrategy( function(username, ...

What steps are necessary to create an npm package utilizing three.js without any dependencies?

I have a challenge - I am trying to create an npm package that generates procedural objects for three.js. The issue I'm facing is how to properly include three.js in my code. I attempted to establish a dependency and use something like const THREE = r ...

Error encountered while running React Native on an iOS device

When attempting to run React Native code on my iPhone, I encountered the following error message. The code runs smoothly on Android and Expo, but it fails to execute on a physical device. I would greatly appreciate any assistance provided. E:\reac ...

Executing a function enclosed in parenthesis does not yield any output

My code is supposed to print the sender's name followed by "adopted" and then the first mentioned user. const { Client } = require('discord.js', 'async', 'discord-message-handler'); const bot = new Client(); const cfg = ...

Troubles with Angular Js: Issues with using $http.put with absolute URLs

Having an issue with $http.put in AngularJS. My server is built with Node.js and my app is in AngularJS. I am trying to make requests from AngularJS to access data on the Node.js server (same host). This code works: $http.put("/fraisforfait", elements); ...

Import a file in Vue only if the file exists under certain conditions

For my project, I need to import a file only when an environment variable is set - let's say dist/built.esm.js. The file will definitely exist when the environment variable is set, but it may or may not exist otherwise. My initial idea was to simply w ...

What is the return value of multer's single() method?

I found a solution on how to manage errors with multer, but I am struggling to grasp its process. var multer = require('multer') var upload = multer().single('avatar') app.post('/profile', function (req, res) { upload(req, res ...

Having trouble connecting to the node server from the vue.js development environment

I am currently working on a Vue project where the source code is located in the vue app directory and the backend file is server.js: /dist /src server.js When I start the project using npm run serve, Vue.js runs on port 8080. However, when I start serve ...

"Utilizing node.js to create a custom regular expression for removing anchor tags

Can someone provide me with a regex pattern that can eliminate all the a tags from HTML and display the URL as plain text? For instance, take this text: abc <a href="http://a.com" target="_blank">bbb</a> ccccccc After applying the regex patt ...

The Node.js application that uses Express and connects to a MSSQL database is reporting that the database

One of my other applications utilizes express and routes, but for this new app I wanted to simplify it. Despite being confident in the correctness of the connection string, I encountered an issue. script.getQuestions(connection); script.getQuestions = fu ...

Tips for setting up Express to consistently serve Angular while safeguarding API routes

I need to set up my node-express back-end so that it serves Angular files by default, but handles API routes differently. All API routes should be protected, with the exception of /api/signin and /api/changepass. I suspect that the order of my code is cau ...

Develop your project with Angular 2 using the powerful Angular CLI build tool

Hello there! I am new to Angular 2 and recently developed a small project with the help of angular-cli for packaging. The dist folder was generated successfully. However, when I deployed the app to the server and tried to access the index.html page, it co ...

node.js throwing an unexpected callback error

var http = require("http"); var fs = require("fs"); http.createServer(function (req, res) { fs.readFile("demo1.html", function (err, data) { res.writeHead(200, { "Content-Type": "text/html" }); ...

Facing difficulties in initiating Selenium with PhantomJS/GhostDriver as child processes

I am currently working on a Node script that involves using the child_process module in order to run a Selenium server with PhantomJS's GhostDriver. I have imported the module: Child = require "child_process" This is how I am attempting to start the ...

Error occurred while searching for the production build in Dockerfile for Next.js application

While testing a production dockerfile, I encountered an error message that reads as follows: Error: Could not locate a production build in the '/app/.next' directory. Please make sure to build your app using 'next build' before starting ...