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 }, ];
Advertisement
Answer
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 });