MongoDB筛选当两个字段相等时

huangapple go评论52阅读模式
英文:

MongoDB filter when two fields equal

问题

{ "history_doc.data.objectId": { "$eq": "_id" } }
{ "history_doc.data.objectId": { "$eq": { "$toString": "_id" } } }
英文:

MongoDB筛选当两个字段相等时

Does anyone who knows how to filter data and only keep those history_doc.data.objectId equals _id?

I have tried so many methods but none of them works

{'history_doc.data.objectId': {$eq: '$_id'}}
{'history_doc.data.objectId': {$eq: {$toString: '$_id'}}}

答案1

得分: 0

你可以在聚合查询中像这样使用 $expr$eq$toObjectId

.aggregate({
  $match: {
    $expr: {
      $eq: [
        "_id",
        {
          "$toObjectId": "$history_doc.data.objectId"
        }
      ]
    }
  }
})

示例在这里

英文:

You can use $expr and $eq with $toObjectId into aggregation query like this:

.aggregate({
  $match: {
    $expr: {
      $eq: [
        "$_id",
        {
          "$toObjectId": "$history_doc.data.objectId"
        }
      ]
    }
  }
})

Example here.

答案2

得分: 0

你可以使用聚合框架来完成:

  • $match - 根据自定义条件筛选文档
  • $eq$toString - 用于检查 _idhistory_doc.data.objectId 是否相同。
db.collection.aggregate([
  {
    "$match": {
      "$expr": {
        "$eq": [
          {
            "$toString": "$_id"
          },
          "$history_doc.data.objectId"
        ]
      }
    }
  }
])

工作示例

英文:

You can do it with Aggregation Framework:

  • $match - to filter documents based on some custom criteria
  • $eq and $toString - To check it _id and history_doc.data.objectId are the same.
db.collection.aggregate([
  {
    "$match": {
      "$expr": {
        "$eq": [
          {
            "$toString": "$_id"
          },
          "$history_doc.data.objectId"
        ]
      }
    }
  }
])

Working example

huangapple
  • 本文由 发表于 2023年2月6日 16:05:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75358721.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定