Y
Y
Young_nigilist2021-03-11 13:07:47
MongoDB
Young_nigilist, 2021-03-11 13:07:47

How to get data from nested JSON MongoDB object with nodeJS?

I have JSON object in MongoDB
6049ea2492153497342517.png
I have tried

findOne({'menu.products': 
     {$elemMatch:{
          '_id': 60475de5ce4dd6151019d574
           }
     }})

But it outputs the whole array. It turned out to be as close as possible with this code
distinct('menu.products', { 'menu.products._id': 60475de5ce4dd6151019d574 })

6049eb543c102329249406.png
It already outputs all products, but not the requested one. How can I get the requested product by ID?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Israfil22, 2021-03-11
@Young_nigilist

There is no need to store data like this, this is an unnormalized base, it’s better to redo it before it’s too late.
In particular, products must be links to another data collection. Your problem arises precisely for this reason.

// api: collection.find{filter, options}
myCollection.find({
  'menu.products': {
    $in: {
      {
        '_id': 60475de5ce4dd6151019d574
      }
    }
  }
}, {
  projection: {
    'menu.products': 1
  }
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question