I've looked around and I see a lot of similar questions, but I don't quite understand why my code isn't working. I'm fairly new to MongoDB, so I may be using something incorrectly. I'm basically just trying to select a random document but filter out the ones that are passed through an array. In the request body, we have this posting to the server:
{
"chosen_lists": ["62718d522a2b7790b4052331"]
}
And I have my code as such to try and filter and return any one random document that does not have that id, like so:
const chosenLists = req.body.chosen_lists;
list = await List.aggregate([
{ $match: { _id: { '$nin': chosenLists } }},
{ $sample: { size: 1 } }
], (err, docs) => docs);
Unfortunately the server returns just one randomly selected document and not filtering it out. I've also added quotes around _id
but that did not seem to work either. Thank you ahead of time for your help!
Edit: I'm current passing the ids for chose_lists as strings, and not ObjectIds. I just tried grabbing the first and converting it into an ObjectId and that did not work either:
list = await List.aggregate([
{ $match: { _id: mongoose.Types.ObjectId(req.body.chosen_lists[0]) } },
{ $sample: { size: 1 } }
], (err, docs) => docs);
CodePudding user response:
If your _id
Property is an ObjectId
you should parse that to String as a following:
const List = await List.aggregate([
{
$project: {
_id: {
$toString: "$_id"
}
}
},
{ $match: { _id: { '$nin': chosenLists } }},
{ $sample: { size: 1 } }
]);
Note: The field name _id is reserved for use as a primary key; its value must be unique in the collection, is immutable, and may be of any type other than an array as default mongo use it as ObjectId
.