Steven Selolo
Steven Selolo

Reputation: 161

How to query nested object in mongodb

I'm new to mongodb and I've been trying to query this doc for awhile now.

Im trying to query all the rooms that have a room name of 100.

json

{
"count": 3,
"reviews": [
    {
        "_id": "5f9d42a0a8e71e004643f584",
        "user": {
            "_id": "5f7308cde0a4a7a66bc3d184",
            "name": "Guest"
        },
        "room": {
            "_id": "5f98f9321fd5bb0045b3d886",
            "name": "100",
        },
        "rating": 4,
    },
    {
        "_id": "5f9d431ea8e71e004643f585",
        "user": {
            "_id": "5f7308cde0a4a7a66bc3d184",
            "name": "Guest",
        },
        "room": {
            "_id": "5f98f9321fd5bb0045b3d886",
            "name": "100",
        },
        "rating": 5,
    },
    {
        "_id": "5f9e74fea6c06a0046d3cae2",
        "user": {
            "_id": "5f7308cde0a4a7a66bc3d184",
            "name": "Guest",
        },
        "room": {
            "_id": "5f98fa8b1fd5bb0045b3d88a",
            "name": "300",
        },
        "rating": 5,   
    }
]}

what I've tried

1. find({},{"reviews.room.name": {$eq: "100"}}) // getting a projection error
2. find({"reviews.room.name": "100"}) // getting null

Any help to the right direction would be greatly appreciated.

Upvotes: 0

Views: 1348

Answers (2)

Artem Fedotov
Artem Fedotov

Reputation: 452

Check out the docs about how to use find: https://docs.mongodb.com/manual/reference/method/db.collection.find/

and try this

db.reviews.find({
  "room.name": "100"
})

Here is the playground with your example: https://mongoplayground.net/p/dPfH5fSOePq

Upvotes: 1

mouheb
mouheb

Reputation: 99

did u try this ? const response = await Room.find({name: "100"})

Upvotes: 0

Related Questions