joe.hart
joe.hart

Reputation: 205

How to exclude an array of objects from mongoose find?

Lets pretend my collection holds following elements:

const Item = mongoose.Schema({
   type: { type: String },
   group: { type: Number }
});

[
   { type: "A", group: 1 },
   { type: "B", group: 1 },
   { type: "C", group: 1 },
   { type: "A", group: 2 },
   { type: "B", group: 2 },
   { type: "C", group: 2 },
]

Now I want to execute a find operation but want to exclude following items:

const items = [
    { type: "A", group: 1 },
    { type: "B", group: 1 },
];

const result = await Model.find({ /* ??? */ });

How does the query have to look to get the following response?

const result = [
   { type: "C", group: 1 },
   { type: "A", group: 2 },
   { type: "B", group: 2 },
   { type: "C", group: 2 },
];

Upvotes: 2

Views: 754

Answers (1)

turivishal
turivishal

Reputation: 36144

Try $nor operator, performs a logical NOR operation on an array of one or more query expression and selects the documents that fail all the query expressions in the array.

const items = [
    { type: "A", group: 1 },
    { type: "B", group: 1 },
];
const result = await Model.find({ $nor: items });

Playground

Upvotes: 1

Related Questions