简体   繁体   中英

MongoDB query for field in embedded document in array

I have a document where stock prices are saved in an embedded document within an array in MongoDB. I need to get one stock price, depending on the date, and both display in the template and also use in further calculations.

I have a Meteorpad with an example. The helper to get the stock price starts at /client/app.js line 25, using the code from @Hakan Kose's answer. Not sure how to change the last line though ( console.log won't work here).

For 2015-12-01, the query should return 117.34 .

{
  ticker: "AAPL",
  valuationDate: "2015-12-01",
  closingPrices: [
    {date: "2015-12-01", close: "117.34"},
    {date: "2015-12-02", close: "116.28"},
    {date: "2015-12-03", close: "115.20"},
    {date: "2015-12-04", close: "119.03"}
  ]
}

Thank you for any assistance.

You can do this easyly with;

Valuations.findOne({_id:this._id}, function(data){
   data.closingPrices.forEach(function(closingPrices){
       if(closingPrices.date === valuationDate){
           console.log(closingPrices.close)
       }
   });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM