Mongoose查找 - 排除一个特定的文档

11

我想通过Schema.find()获取多个文档,但是排除一个特定的文档(通过其id)。目前,我的查询如下:

Product
    .find({
        $or: [
            { 'tags': { $regex: criteria, $options: 'i' }, },
            { 'name': { $regex: criteria, $options: 'i' }, },
        ],
    })
    .limit(10)
    .exec((err, similar) => {
        //...
    })

我试图在查询中添加$not: { _id: someId },但是这给了我一个错误,说$not无效。


1
要使用$not,您应该指定运算符: Product.find({ _id: {$not: {$eq: someId}}}) - Ron537
2个回答

25

使用$ne表示不等于

Product.find({ _id: {$ne: someId}})

因此,整个查询看起来像:

Product
    .find({
        $and: [
             { _id: {$ne: someId} },
             { $or: [
                   { 'tags': { $regex: criteria, $options: 'i' }, },
                   { 'name': { $regex: criteria, $options: 'i' }, },
             ]},
         ]
    })
    .limit(10)
    .exec((err, similar) => {
        //...
    })

有没有一种方法可以排除多个ID? {$ne:someId,someIdAgain}不起作用 :/ - Eray T
没事了,我找到了。我使用了你的第二个例子,并以此添加了更多的id。谢谢。 - Eray T
我正在使用 "mongoose": "^5.3.12",但它无法运行。 - 151291

1
对于在mongooses中不等于多个Id的情况。
const products = await Product.find({
  _id: { $nin: [id1, id2, id3] },
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接