1

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.

1
  • You can fire two queries if you don't want aggregation Commented Feb 2, 2022 at 17:03

2 Answers 2

1

you can use the $and like this:

const found = await User.find({
    $and: [
      { _id: { $in: array1 } },
      { _id: { $nin: array2 } }
    ]
  });
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help ... your answer is kinda what I already wrote, but when I used to add a new element to the array I didn't initialize the "_id" so mongo gives a default _id to each new element ... all I had to do is modify that custom behavior and initialize the _id with the user's _id.
1

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 } });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.