关于猫鼬中的对象的查询数组

时间:2020-03-07 08:28:14

标签: mongodb mongoose

mongoplayground中进行测试

https://mongoplayground.net/p/c3UBL9JwX5u

期望

{
  _id: "5df1e6f75de2b22f8e6c30e8",
  t: [
    { name: "d1", tt: false },
    { name: "d2", tt: true } 
  ]
}

这是我的查询

db.coll.find({
  "t": {
    $ne: {
      "name": {
        $regex: "d1",
        $options: "g"
      },
      "tt": true
    }
  }
})

我得到了错误的答案,那么如何获得期望的结果呢?谢谢!

  1. t.name包括'd1'和t.tt!= true
  2. t.name不包含“ d1”

我想要得到结果1 or 2

1 个答案:

答案 0 :(得分:0)

https://mongoplayground.net/p/CnGnSmRzXCB

db.coll.find({
  $or: [
    {
      "t": {
        $elemMatch: {
          name: {
            "$regex": "^d1$|d1"
          },
          tt: false
        }
      }
    },
    {
      "t": {
        $not: {
          $elemMatch: {
            name: {
              $regex: "d1"
            },

          }
        }
      }
    }
  ]
})