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.

DD DD
  • 1,148
  • 1
  • 10
  • 33

3 Answers3

1
const result  = await YourSchemaModelName.findOne({
                                                   "color": "gray", 
                                                   "object.name": { "$eq" : "apple"}
                                                  });
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

rantao
  • 1,621
  • 4
  • 14
  • 34
0

You can use :

const result = await Model.findOne({color: "gray", "object.name":"apple" });
Joel Joseph
  • 5,889
  • 4
  • 31
  • 36