Home > Back-end >  How to use MongoDB $in in aggregation
How to use MongoDB $in in aggregation

Time:11-11

I'm querying my MongoDB collection of hotels, and I need to create a $match stage, where I only keep documents, which have at least one room, that matches each $in

A sample document in my collection:

{
  title: "Lorem ipsum",
  rooms: [
    {
       type: "shelter",
       spots: 2
    },
    {
       type: "box",
       spots: 1
    },
    {
       type: "house",
       spots: 5
    },
  ]
}

This $match stage works:

{
  "rooms.type": {
    $in: ["shelter"]
  }
  "rooms.type": {
    $in: ["box"]
  }
}

But I can't create an object with two identical keys in Javascript. So I need to send it like this from my NodeJS API. But how come this doesn't work?:

{
  $expr: {
    $or: [
      { $in: ["$rooms.type", ["shelter"]] },
      { $in: ["$rooms.type", ["box"]] }
    ]
  }
}

CodePudding user response:

If I've understood correctly you can add an $or stage to create the conditions like this:

db.collection.aggregate([
  {
    "$match": {
      "$or": [
        {
          "rooms.type": {"$in": ["shelter","first","array"]}
        },
        {
          "rooms.type": {"$in": ["box","second","array"]}
        }
      ]
    }
  }
])

This query will returns documents which field rooms.type contains values that exists into one of the two arrays.

Example here

  • Related