MongoDB聚合使用’and’、’or’和’in’条件

huangapple go评论61阅读模式
英文:

MongoDB aggregation with 'and' and 'or' and 'in' conditions

问题

{ "$match": { "$and": [ { "is_active": { "$eq": True }}, { "is_delete": { "$eq": False }}] } }

这是我的查找聚合的匹配条件,它正常工作。

现在我需要添加另外两个条件,这些条件不是必填字段,它们可以是null或者不是,我认为我需要在内部使用or条件,在顶层查询时使用and条件,当我传递abc和xyz时,它正常工作,如果我没有传递其中一个或者两者都没有传递,它会失败(没有返回正确的数据)。

{ "abc_id" : { "$eq": abc } },{ "xyz_id" : {"$in": [xyz]} }

我该如何实现这个?感谢您的建议。

英文:
{ "$match": { "$and": [ { "is_active": { "$eq": True }},{ "is_delete": { "$eq": False }}] } }

This is my match condition for lookup aggregation and it is working fine.

Now I need to add two more conditions and these are not mandatory fields they may be null or not, I think I need or condition inside, with and condition as top query when I pass abc and xyz, it is working, if I didn't pass both or anyone its failing (not returning proper data).

{ "abc_id" : { "$eq": abc } },{ "xyz_id" : {"$in": [xyz]} }

How can I achieve this? Thanks for inputs.

答案1

得分: 1

{
"$match": {
"$and": [
{ "is_active": { "$eq": True } },
{ "is_delete": { "$eq": False } },
{
"$or": [
{ "abc_id": { "$eq": abc } },
{ "xyz_id": { "$in": [xyz] } }
]
}
]
}
}

英文:

You can includ or :

{
  "$match": {
    "$and": [
      { "is_active": { "$eq": True } },
      { "is_delete": { "$eq": False } },
      {
        "$or": [
          { "abc_id": { "$eq": abc } },
          { "xyz_id": { "$in": [xyz] } }
        ]
      }
    ]
  }
}

huangapple
  • 本文由 发表于 2023年3月8日 17:58:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75671586.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定