首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在MongoDB中传递条件值来查询?

如何在MongoDB中传递条件值来查询?
EN

Stack Overflow用户
提问于 2021-11-03 12:58:22
回答 1查看 56关注 0票数 0

我是MongoDB的新手。我在编写以下过滤器逻辑时遇到了问题。你能帮我一把吗。=>

如果isNightParty:true,签入DB for isNightParty :true并返回其他所有文档,不要检查

这是我的代码:

代码语言:javascript
复制
    router.get("/hotelList", (req,res) =>{
      const {date, boys, girls, isNightParty} = req.body
      businessUser.find(
      {
        $and:[
        {isBlockedOn:{$ne:date}},
        //{girlsWithBoys:isGirlsWithBoys},
        {"isNightPartyAllowed":{$exists:true}}
      }
        ).then((toListHotels)=>{
        return (res.status(200).json(toListHotels))  
      })
      .catch((err)=>{
          console.log(err)
        })
    
    })

我的DB结构如下:

代码语言:javascript
复制
{
    "_id": {
      "$oid": "6182603cce3b3b92991fee96"
    },
    "hotelName": "Hotel",
    "email": "hotel1@hotel.com",
    "password": "$2a$12$RXr2xTbnGP2ASUTqP2ptQOtS36QOr0.uq/OHTuIRLigYUM..T3lb6",
    "location": "url",
    "address": "address",
    "isNightPartyAllowed": true,
    "girlsWithBoys": true,
    "roomSmallData": {
      "smallPrice": "1000",
      "smallPic": "url",
      "smallCapacity": {
        "$numberInt": "5"
      },
      "_id": {
        "$oid": "6182603cce3b3b92991fee97"
      }
    },
    "roomMediumData": {
      "mediumPrice": "2000",
      "mediumPic": "url",
      "mediumCapacity": {
        "$numberInt": "7"
      },
      "_id": {
        "$oid": "6182603cce3b3b92991fee98"
      }
    },
    "roomLargeData": {
      "largePrice": "3000",
      "largePic": "url",
      "largeCapacity": {
        "$numberInt": "10"
      },
      "_id": {
        "$oid": "6182603cce3b3b92991fee99"
      }
    },
    "__v": {
      "$numberInt": "0"
    },
    "isBlockedOn": [
      "Fri Nov 05 2021 00:00:00 GMT+0530 (India Standard Time)"
    ]
  }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-03 14:08:51

使用$or来满足以下两个条件:

  1. 输入isNightParty为空
  2. isNightPartyAllowed为真,这两种情况都应该允许返回文档。
代码语言:javascript
复制
db.collection.aggregate([
  {
    $match: {
      $expr: {
        $or: [
          // put your parameter <isNightParty> here
          {
            $eq: [
              null,
              <isNightParty>
            ]
          },
          {
            $eq: [
              {
                "$ifNull": [
                  "$isNightPartyAllowed",
                  false
                ]
              },
              true
            ]
          }
        ]
      }
    }
  }
])

这是供您参考的蒙戈游乐场

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69825279

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档