0

From this 'houses' collection

{
  _id: "0",
  rooms: [
    {
      roomName: "living-room"
      chairs: "6"
    },

    {
      roomName: "kitchen"
      chairs: "0"
    }
  ]
}

I need to find the house with _id = 0, and select only the 'chairs' from the "living-room" so that the result looks like this:

{
  chairs: 6
}

I think of something that looks like this: House.findOne({_id: '0'}).select('rooms.chairs') // but only from {roomName: "living-room"} How do I complete the query?

2 Answers 2

1

How about this one:

db.houses.aggregate([
   { $match: { _id: "0" } },
   {
      $project: {
         chairs: {
            $filter: {
               input: "$rooms",
               cond: { $eq: ["$$this.roomName", "living-room"] }
            }
         }
      }
   },
   {
      $replaceRoot: {
         newRoot: {
            chairs: { $arrayElemAt: ["$chairs.chairs", 0] }
         }
      }
   },
])
Sign up to request clarification or add additional context in comments.

1 Comment

Fantastic! I applied this to my situation and it works! Therefore I mark this as the answer.
0
db.house.findOne({"rooms.chairs":"6"},{"rooms.$":1})

1 Comment

To clarify more, the point of the query should be to find and select only chairs, and not query by it's value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.