简体   繁体   English

如何在 mongoose 的数组中返回匹配的 object

[英]How to return a matched object inside an array in mongoose

{
  "_id": 36546b46bbh343..,
  "name": "Mike",
  "Friends: [
    {"name":"lora","age":23},
    {"name":"test","age":26}
  ]
}

I know that if we do我知道如果我们这样做

dbname.find({
  Friends:{
    $elemMatch:{
      "name": "test", 
      "age": 26
    }
  }
})

It will return the whole document with all the objects.它将返回包含所有对象的整个文档。 But what I have been searching for is there any method so that I can get only the object that matches it.但是我一直在寻找的是有什么方法可以让我只得到与之匹配的 object。

Try this尝试这个

 db.collection.find({
      Friends: {
        $elemMatch: {
          "name": "test",
          "age": 26
        }
      }
    },
    {
      "Friends.$": 1
    })

Demo演示

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

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