Mongodb: 查找至少在一个数组中存在的项目在数组字段中的文档

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

Mongodb: find documents where at least one item in an array exists in an array field

问题

Here is the translated code snippet using $match and $expr:

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $in: [
          "$favorites",
          [
            "apple",
            "orange"
          ]
        ]
      }
    }
  }
])

Please note that this code snippet should find documents in the collection where the "favorites" field contains either "apple" or "orange." If it's not returning any results, you may want to double-check your data and ensure that it matches the expected structure.

英文:

This is my data:

[
  {
    "_id": 1,
    "name": "Alice",
    "favorites": [
      "apple",
      "banana",
      "cherry"
    ]
  },
  {
    "_id": 2,
    "name": "Bob",
    "favorites": [
      "banana",
      "orange"
    ]
  },
  {
    "_id": 3,
    "name": "Charlie",
    "favorites": [
      "apple",
      "cherry"
    ]
  }
]

and I need to find the documents that have for example apple or orange in favorites field.
I know this works:

    db.collection.aggregate([
      {
        $match: {
             favorites: {
             $in: [
               "apple",
               "orange"
              ]
         }
        }
      }
    ])

also I know how to do it with find().

I need to do it with $match and $expr like:

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $in: [
          "$favorites",
          [
            "banana",
            "orange"
          ]
        ]
      }
    }
  }
])//Returns no data

but returns no result.

答案1

得分: 0

  1. $ne - 检查1.1的结果不是空数组。

1.1. $setIntersection - 对favorite和输入数组进行交集操作,返回一个包含交集的数组。

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $ne: [
          {
            $setIntersection: [
              "$favorites",
              [
                "banana",
                "orange"
              ]
            ]
          },
          []
        ]
      }
    }
  }
])

演示 @ Mongo Playground

英文:

In case you are still keen on working the query with $expr operator,

  1. $ne - Check the result from 1.1 not an empty array.

1.1. $setIntersection - Intersect the favorite and input array to return an array with intersection.

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $ne: [
          {
            $setIntersection: [
              "$favorites",
              [
                "banana",
                "orange"
              ]
            ]
          },
          []
        ]
      }
    }
  }
])

Demo @ Mongo Playground

huangapple
  • 本文由 发表于 2023年5月11日 06:50:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76223060.html
匿名

发表评论

匿名网友

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

确定