【问题标题】:Fetch records if field exists in mongodb如果 mongodb 中存在字段,则获取记录
【发布时间】:2016-10-10 19:49:47
【问题描述】:

我有这个问题

db.invites.find({$and: [{primaryowner: mynumber}, {invited: mynumber}]})

如果满足上述条件,我将使用它来获取记录。但是,我想获取 {eventtype:4} 和字段 primaryowner:$exists: true 的记录

这就是我所拥有的

{ eventtype: 4 },{ primaryowner: { $exists: true }}

但我知道这不是因为我需要获取 eventtype = 4 和字段 primaryowner 存在的记录。

如何表示查询?

【问题讨论】:

  • 你要db.invites.find({$and: [{eventtype: 4}, { primaryowner: { $exists: true }}]})吗?你的问题真的不清楚...
  • 在此处发布您的示例文档和您的预期输出
  • @ClementAmarnath 这是我的声明db.invites.find({invited:"0800123456",{$and: [{eventtype: "4"},{primaryowner: { $exists: true }}]}.pretty() 我希望获得被邀请为 0800123456 且 eventtype = 4 的记录,其中该行有一个字段 primaryowner
  • 您得到预期的响应了吗?还发布您收藏的示例文档
  • @ClementAmarnath 好的,我正在发布一些数据。

标签: mongodb


【解决方案1】:

根据您的问题,我无法清楚地了解所需的业务场景是什么,但提供的示例数据 我已经给出了一个伪代码和该伪代码的相应 mongodb 实现。

if invited field is "0800123456" 
   if event type is 3 and event status is 11
     select matching documents
or if event type is 4 and event status is 11 and primary owner exists
     select matching documents

Mongo 数据库查询

db.collection.find({
  $or: [
    {
      $and: [
        {
          "invited": "0800123456"
        },
        {
          "eventtype": {
            $eq: "3"
          }
        },
        {
          "eventstatus": {
            $eq: 11
          }
        }
      ]
    },
    {
      $and: [
        {
          "eventtype": {
            $eq: "4"
          }
        },
        {
          "eventstatus": {
            $eq: 11
          }
        },
        {
          primaryowner: {
            $exists: true
          }
        }
      ]
    }
  ]
})

如果这与您的方案不匹配,请在此示例代码的帮助下编写您自己的查询。

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 2020-11-25
    • 2018-02-05
    • 2012-03-28
    • 2022-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 2022-07-20
    相关资源
    最近更新 更多