Search code examples
mongodbmongoosenosqlkey-value

MongoDB query to find all pairs given as input


Input example:

db.students.insertMany([
  { id: 1, name: "Ryan", size: "M", color: "blue" },
  { id: 2, name: "Joanna", size: "S", color: "red" },
  { id: 3, name: "Andy", size: "M", color: "green" },
  { id: 4, name: "Irina", size: "L", color: "red" },
  { id: 5, name: "Nick", size: "S", color: "blue" },
  { id: 6, name: "Ricky", size: "M", color: "green" },
  { id: 7, name: "Dawn", size: "L", color: "red" }
]);

I would like (if possible) with a single query to be able to search for the following pairs and put them in a single array in MongoDB (or mongoose): (M, blue), (M, green), (L, red)

Desired output:

[
  { id: 1, name: "Ryan", size: "M", color: "blue" },
  { id: 3, name: "Andy", size: "M", color: "green" },
  { id: 4, name: "Irina", size: "L", color: "red" },
  { id: 6, name: "Ricky", size: "M", color: "green" },
  { id: 7, name: "Dawn", size: "L", color: "red" }
]

I only managed to search for each pair in turn and concatenate the arrays.

db.myCollection.find({"size":"M", "color":"blue"})
... concat
db.myCollection.find({"size":"M", "color":"green"})
... concat
db.myCollection.find({"size":"L", "color":"red"})

Solution

  • Solution by @Noel comment:

    db.students.find({ 
        $or: [{
                    size: "M", color: "blue"
                },
                {
                    size: "M", color: "green"
                },
                {
                    size: "L", color: "red"
                }
            ]
    });