Mongodb通过比较两个ObjectId类型的字段来查找记录
Monogdb find records by comparing two fields of type ObjectId
我有一个查询,当我在 MongoDB Compass 实用程序中 运行 时它工作正常:
{ $where: "if (this.media && this.media.length > 1 && this.status=='Published') {return this; } "}
在同一个集合中或 table 我还有两个字段 createBy 和 userId
现在我想过滤 createdBy 与 userId 不同的记录。我试试这个:
{ $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; } "}
但是none以上两个作品。我知道 ObjectId 是 Object 类型,比较具有完全相同值的对象是行不通的。只是不知道如何在 mongodb 查询控制台中比较它。
如果您使用的是 Mongodb 版本 >= 3.6,您可以尝试 $expr
操作,因为它比 $where
更快。
要比较 ObjectId
,您可以使用 .equals()
方法或在两个 ObjectId
上调用 .toString()
进行比较
{ $where: "if (this.media && this.media.length > 1 && this.status=='Published' && !this.userId.equals(this.createdBy)) {return this; } "}
我认为你需要 .toString()
方法来比较两个 ObjectIds
尝试:
this.userId.toString()!= this.createdBy.toString()
另一种选择是使用 .equals()
this.userId.equals(this.createdBy)
在此处阅读有关 .equals() and .toString() 的更多信息。
我有一个查询,当我在 MongoDB Compass 实用程序中 运行 时它工作正常:
{ $where: "if (this.media && this.media.length > 1 && this.status=='Published') {return this; } "}
在同一个集合中或 table 我还有两个字段 createBy 和 userId
现在我想过滤 createdBy 与 userId 不同的记录。我试试这个:
{ $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; } "}
但是none以上两个作品。我知道 ObjectId 是 Object 类型,比较具有完全相同值的对象是行不通的。只是不知道如何在 mongodb 查询控制台中比较它。
如果您使用的是 Mongodb 版本 >= 3.6,您可以尝试 $expr
操作,因为它比 $where
更快。
要比较 ObjectId
,您可以使用 .equals()
方法或在两个 ObjectId
上调用 .toString()
进行比较
{ $where: "if (this.media && this.media.length > 1 && this.status=='Published' && !this.userId.equals(this.createdBy)) {return this; } "}
我认为你需要 .toString()
方法来比较两个 ObjectIds
尝试:
this.userId.toString()!= this.createdBy.toString()
另一种选择是使用 .equals()
this.userId.equals(this.createdBy)
在此处阅读有关 .equals() and .toString() 的更多信息。