mongodb:数组中的值查询文档

发布于 01-23 20:42 字数 485 浏览 2 评论 0原文

我有这些文档:

{"_id" : 1, "actors" : [{"matricule" : "AVB", "name":"XXX"}, {"matricule" : "AVB", "name":"YYY"}]}
{"_id" : 2, "actors" : [{"matricule" : "PMH", "name":"FFF"}, {"matricule" : "BNG", "name":"HHH"}]}

我只想获取第一个文档,因为它是相同的矩阵,但名称不同。

我使用此查询:

{
 $expr:{$eq:["$actors.0.matricule", "$actors.1.matricule"]}
}

但是它不起作用,我没有任何结果。 你知道为什么吗?

I have those documents :

{"_id" : 1, "actors" : [{"matricule" : "AVB", "name":"XXX"}, {"matricule" : "AVB", "name":"YYY"}]}
{"_id" : 2, "actors" : [{"matricule" : "PMH", "name":"FFF"}, {"matricule" : "BNG", "name":"HHH"}]}

I would like to get only the first document because it's the same matricule but a different name.

I use this query :

{
 $expr:{$eq:["$actors.0.matricule", "$actors.1.matricule"]}
}

But it doesn't work, I don't have any results.
Do you know why ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

探春 2025-01-30 20:42:19

尝试使用$ arrayElemat

db.collection.find({
  $expr: {
    $eq: [
      {
        "$arrayElemAt": [
          "$actors.matricule",
          0
        ]
      },
      {
        "$arrayElemAt": [
          "$actors.matricule",
          1
        ]
      }
    ]
  }
})

这是 mongo Playgrounger 供您参考。

Try to use $arrayElemAt

db.collection.find({
  $expr: {
    $eq: [
      {
        "$arrayElemAt": [
          "$actors.matricule",
          0
        ]
      },
      {
        "$arrayElemAt": [
          "$actors.matricule",
          1
        ]
      }
    ]
  }
})

Here is the Mongo playground for your reference.

倾其所爱 2025-01-30 20:42:19

查询

  • “ $ actors.matricule”是所有这些矩阵值的数组,
  • 使其成为集合(与空数组的联合)=>没有重复的
  • 过滤器仅保留一个尺寸1(所有具有相同值的人)

*如果您在演员阵列中有一个或多个成员

Playmongo

aggregate(
[{"$match": 
   {"$expr": 
     {"$eq": [{"$size": {"$setUnion": ["$actors.matricule", []]}}, 1]}}}])

Query

  • "$actors.matricule" is an array of all those matricule values
  • make it a set (union with the empty array)=> no duplicates
  • filter to keep only those with size 1 (all have the same value)

*can work if you have one or many members inside the actors array

Playmongo

aggregate(
[{"$match": 
   {"$expr": 
     {"$eq": [{"$size": {"$setUnion": ["$actors.matricule", []]}}, 1]}}}])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文