MongoDB-查找具有几个条件的文档

发布于 2025-01-25 20:57:17 字数 835 浏览 2 评论 0原文

要求: 计算集合中的所有文档 objects.ObjectType等于“组” 和 (objects.ObjectType不等于'person'&&&关系等于“ exposed_to”)

预期:将返回所有文档的计数 。 &房地产:exposed_to)在“对象”阵列下。

匹配文档的一个示例:

"objects": [
    {
    "objectType": "organization",
    "relation": "Exposed_to"
    },
    {
    "objectType": "group",
    "relation": "Exposed_to"
    }
]

不应该计算的文档的示例:

"objects": [
    {
    "objectType": "person",
    "relation": "Exposed_to"
    },
    {
    "objectType": "group",
    "relation": "Exposed_to"
    }
]

我尝试了以下查询:

.count({
'objects.objectType': 'group',
'objects': {
    $elemMatch: {
    $and: [{'objectType' : {$ne: 'person'}, 'relation': 'Exposed_to'}]
    }
}})

但是它似乎无法正常工作。 在这种情况下,我不确定是否应该使用聚合 - 我在这方面的知识也更少。

我很高兴获得一些帮助。谢谢!

Requirement:
COUNT all documents in the collection WHERE
objects.objectType equal to 'group'
AND
(objects.objectType NOT equal to 'person' && relation equal to 'Exposed_to')

Expected: will return count of all documents WHERE objects.objectType equal to 'group' AND which does not contain any (objectType:person && realtion:Exposed_to) under 'objects' array.

An example of matched document:

"objects": [
    {
    "objectType": "organization",
    "relation": "Exposed_to"
    },
    {
    "objectType": "group",
    "relation": "Exposed_to"
    }
]

An example of document that shouldn't be counted:

"objects": [
    {
    "objectType": "person",
    "relation": "Exposed_to"
    },
    {
    "objectType": "group",
    "relation": "Exposed_to"
    }
]

i have tried the following query:

.count({
'objects.objectType': 'group',
'objects': {
    $elemMatch: {
    $and: [{'objectType' : {$ne: 'person'}, 'relation': 'Exposed_to'}]
    }
}})

but it seems to be not working correctly.
i am not sure if i should use aggregation in this case- i also have less knowledge in this area.

i will be glad to get some help. thanks!

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

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

发布评论

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

评论(1

命硬 2025-02-01 20:57:17

它对您有用吗? https://mongoplayground.net/p/q-dj7_o_ajr
这个操场不支持Count,因此我替换为查找

db.collection.find({
  $and: [
    {
      "objects.objectType": "group"
    },
    {
      objects: {
        $not: {
          "$elemMatch": {
            "objectType": "person",
            "relation": "Exposed_to"
          }
        }
      }
    }
  ]
})

Is it working for you? https://mongoplayground.net/p/Q-dj7_O_AJR
This playground doesn't support count, so I replace by find

db.collection.find({
  $and: [
    {
      "objects.objectType": "group"
    },
    {
      objects: {
        $not: {
          "$elemMatch": {
            "objectType": "person",
            "relation": "Exposed_to"
          }
        }
      }
    }
  ]
})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文