简体   繁体   English

MongoDB通过ID数组中的findOne对象

[英]Mongodb findOne object in array by id

Im trying to find a specific entry to my database document by the users id and the by the selected field and item. 我正在尝试通过用户标识以及选定的字段和项来查找数据库文档的特定条目。 I would like the items object to be returned. 我希望返回项目对象。 This is the document structure: 这是文档结构:

{
"_id": ObjectId("58edfea4b27fd0547375eeb4"),
"user_id": ObjectId("58d2dd4c8207c28149dbc748"),
"calories": 2000,
"date": 20170312,
"snacks": [ ],
"dinner": [
 {
  "nutrients": {
    "protein": "11.6",
    "carbs": "29.4",
    "fat": "7.9"
  },
  "servings": "75",
  "calories": 750,
  "name": "Meat feast stone baked pizza"
}, 
{
  "nutrients": {
    "protein": "6.8",
    "carbs": "54",
    "fat": "30.6"
  },
  "servings": "25",
  "calories": 550,
  "name": "Mc Coy's Cheddar and onion"
}],
"lunch": [],
"breakfast": [],
}

What I have done so far is get the users id, date and then the selected meal and item to search for. 到目前为止,我要做的是获取用户ID,日期,然后选择要搜索的餐点和食物。 What im getting returned is the entire meal array however I only want the food items object returned. 我要返回的是整个膳食数组,但是我只想返回食物对象。

user_food.findOne({user_id : req.session.user_id, date: today},{'dinner': 'Meat feast stone baked pizza'},function(err, item){
        if(err){
            console.log("something went wrong: " + err);
            return res.status(500).send(err);
        }
        else{
            console.log(item);
            return res.status(200).send(item);
        }
    });

What im getting returned is this: 我得到的回报是:

"dinner": [
{
  "nutrients": {
    "protein": "11.6",
    "carbs": "29.4",
    "fat": "7.9"
  },
  "servings": "75",
  "calories": 750,
  "name": "Meat feast stone baked pizza"
}, 
{
  "nutrients": {
    "protein": "6.8",
    "carbs": "54",
    "fat": "30.6"
  },
  "servings": "25",
  "calories": 550,
  "name": "Mc Coy's Cheddar and onion"
}]

what I want is simply: 我想要的只是:

    {
  "nutrients": {
    "protein": "11.6",
    "carbs": "29.4",
    "fat": "7.9"
  },
  "servings": "75",
  "calories": 750,
  "name": "Meat feast stone baked pizza"
}

Try this: 尝试这个:

user_food.
findOne({
        user_id : req.session.user_id, 
        date: today,
        'dinner.name': 'Meat feast stone baked pizza'
    },{
        'dinner.$' : 1
},function(err, item){
    ....
});

dinner.$ will only return the dinner items which match the criteria, ie where dinner.name : Meat feast stone baked pizza . dinner.name : Meat feast stone baked pizza dinner.$只会传回符合条件的晚餐项目,例如, dinner.name : Meat feast stone baked pizza

Read about $(positional) operator to know more about limiting the contents of array from query result and returning element matching the query document. 阅读有关$(positional)运算符的信息,以了解有关限制查询结果中的数组内容以及返回与查询文档匹配的元素的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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