【问题标题】:check all filter is exist in database or not检查所有过滤器是否存在于数据库中
【发布时间】:2021-06-27 04:15:00
【问题描述】:

我的 mongodb 集合中有一些数据是这样的:

{"_id":{"$oid":"60603f0075ee1d1cdcd95d1a"},
"store_id":{"$oid":"60603dd675ee1d1cdcd95d18"},
"product_id":{"$oid":"6062f6973f24de12f0264013"}}

我想通过查询,如果列表的所有元素都存在于数据库中,则我的查询是 store_id 的列表

我可以一一检查并使用 findOne ,但我不想一一检查!

更新: 我可以通过 for 和 findOne 做到这一点,但我不想向 db 发送大量查询!

【问题讨论】:

  • 您能否包括一些预期的输出。
  • @DheemanthBhat 输出类似这样的信息,以了解数据库中存在的所有数据:{status : True} 或 {status : false} 我传递数组,我想得到一个结果!数据库中是否存在所有元素!
  • 您希望该状态字段出现在所有文档中,或者您希望单个对象作为查询输出。
  • @DheemanthBhat 只是单输出!它们都存在与否!

标签: mongodb aggregation-framework pymongo motordriver


【解决方案1】:

我只能想出这个:传递 store_ids 的列表和 store_ids 的数量。按 store_id 过滤项目并计算有多少唯一的 store_id,然后将数字与您在查询中传递的 store_id 的数量进行比较。您可以使用聚合来表达这一点。

如果你使用聚合,你总是会从 MongoDB 返回文档(对象):{'filedA': false},所以你不能只得到false1

storeIds= [123, 1234, 12345];
numStoreIds = storeIds.length;

pipeline=
[{$match: {
  orderId: {$in: storeIds}
}}, {$group: {
  _id: "$storeId"
}}, {$count: 'num'}, {$project: {
  result: {
    $cond: [ { $eq: [ "$num", numStoreIds ] }, true, false]
  }
}}]

db.collection.aggregate(pipeline)

>
{ "result" : true }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 2013-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多