Monogdb通过比较ObjectId

时间:2019-06-28 05:46:12

标签: mongodb mongodb-query mongodb-compass

当我在MongoDB Compass实用程序中运行该查询时,它运行良好:

{ $where: "if (this.media && this.media.length > 1 && this.status=='Published') {return this; } "}

在同一集合或表中,我还有两个字段createBy和userId

enter image description here

现在,我要过滤具有与userId不同的createdBy的记录。我试试这个:

{ $where: "if (this.media && this.media.length > 1 && this.status=='Published' && this.userId != this.createdBy) {return this; } "}

这也是:

{ $where: "if (this.media && this.media.length > 1 && this.status=='Published' && ObjectId(this.userId) != ObjectId(this.createdBy)) {return this; } "}

但是以上两个都不起作用。我知道ObjectId是Object类型的,比较具有完全相同值的对象将行不通。只是不知道如何在mongodb查询控制台中进行比较。

2 个答案:

答案 0 :(得分:1)

如果使用的Mongodb版本> = 3.6,则可以尝试$expr操作,因为它比$where快。

要比较ObjectId,可以使用.equals()方法,也可以在两个.toString()上调用ObjectId进行比较

{ $where: "if (this.media && this.media.length > 1 && this.status=='Published' && !this.userId.equals(this.createdBy)) {return this; } "}

答案 1 :(得分:1)

我认为您需要.toString()方法来比较两个ObjectIds

尝试:

this.userId.toString()!= this.createdBy.toString()

另一种替代方法是使用.equals()

this.userId.equals(this.createdBy)

在此处详细了解.equals().toString()

相关问题