【问题标题】:Monogdb find records by comparing two fields of type ObjectIdMongodb通过比较ObjectId类型的两个字段来查找记录
【发布时间】:2019-06-28 05:46:12
【问题描述】:

我有一个在 MongoDB Compass 实用程序中运行时运行良好的查询:

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

在同一个集合或表中,我还有两个字段 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; } "}

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

【问题讨论】:

  • 你用的是什么版本的mongodb?
  • @Andyk。我正在使用 v4.0.8。 MongoDB Compass 社区版本是 1.17.0。

标签: mongodb mongodb-query mongodb-compass


【解决方案1】:

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

试试:

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

另一种选择是使用.equals()

this.userId.equals(this.createdBy)

在此处阅读有关.equals().toString() 的更多信息。

【讨论】:

  • 有效!谢谢!我正在尝试ObjectId(this.userId).toString() != ObjectId(this.createdBy).toString()
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-21
    • 1970-01-01
    • 2020-02-04
    • 2021-01-06
    • 2017-12-13
    • 2022-01-22
    相关资源
    最近更新 更多