0

I have a data in mongodb like below.

{
   "color":"gray",
   "object": {
       "name": "apple",
       "price": "2000",
       "qu" : "good"
   }
}

And I want to find this data using mongoose in nodejs.

  const result  = await findOne({color: "gray", object:{name:"apple"}})

But it doesn't give anything. How can I use find well to find inside of json object?
Thank you so much for reading it.

1
  • 3
    const result = await findOne({color: "gray", "object.name":"apple" }) Commented Dec 2, 2019 at 11:41

3 Answers 3

1
const result  = await YourSchemaModelName.findOne({
                                                   "color": "gray", 
                                                   "object.name": { "$eq" : "apple"}
                                                  });
Sign up to request clarification or add additional context in comments.

Comments

1

Use dot notation to find nested objects

const result = await Model.find({ 
    "color": "gray",
    "object.name": "apple"
})
.limit(1)

FYI: I used .find() + .limit(1) rather than .findOne() for performance reasons

https://dba.stackexchange.com/questions/7573/difference-between-mongodbs-find-and-findone-calls

Comments

0

You can use :

const result = await Model.findOne({color: "gray", "object.name":"apple" });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.