Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

443
Views
MongoDB: find if ID exist in array of objects

I was wondering, is there a way in MongoDB to get all the documents from one collection excluding those that exists in another, without using aggregation.

Let me explain myself more;

I have a collection of "Users", and another collection where there is an array of objects. Something like this:

User

  }
    "_id": "61e6bbe49d7efc57f895ab50",
    "name": "User 1"
  },
  {
    "_id": "61e6b9239d7efc57f895ab02",
    "name": "User 2"
  },
  {
    "_id": "61cae6176d0d9a36efd8f190",
    "name": "User 3"
  },
  {
    "_id": "61cade886d0d9a36efd8f11a",
    "name": "User 4"
  },

The other collection looks like this:

{
    users: [
        {
           user: {
              "_id": "61e6b9239d7efc57f895ab02",
              "name": "User 2",
           },
           ...

        },
        {
           user: {
              "_id": "61cae6176d0d9a36efd8f190",
              "name": "User 3",
           },
           ...
        },
    ],
},

I would like to get all the users in "array 1" excluding those in "array 2". So the result should be:

    [
        {
           "_id": "61e6b9239d7efc57f895ab02",
           "name": "User 1"
        },
        {
           "_id": "61cae6176d0d9a36efd8f190",
           "name": "User 4"
        },
    ],

So, is there a way to do that without the need to do aggregation.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

you can use the $and like this:

const found = await User.find({
    $and: [
      { _id: { $in: array1 } },
      { _id: { $nin: array2 } }
    ]
  });
over 4 years ago · Santiago Trujillo Report

0

For anyone looking for a solution, if you want to add new element to an array of objects, where you, somehow, forgot to initialize the _id field, remember you have to, because mongo adds that field automatically (to use it for filtering/indexation).

All you have to do, is to write something like this;

const data = Data.create({
    _id: mongoose.Types.ObjectId.createFromHexString(uid),
    users: [{ user: userId, initiator: true, _id: userId}],
})

and for the searching, you write what you always write;

const found = await User.find({ _id: { $nin: data.users } });
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!