Mongoose 在嵌入式文档中获取特定项目

问题描述

我是 Nosql 的新手,有点卡住了。你能帮我吗?

如果匹配一个值,有没有办法获取数组中的特定字段? 例如,我想获取数组 accountGroup 中的特定项,其中 accountGroupName=="Account 1"。

我尝试了很多代码,但它只返回包含与值匹配的项目的整个数组。

顺便说一下,我使用的是 Mongoose 和 Nodejs。谢谢。

   //here is the database    
   {
    "_id" : ObjectId("60d2db4b90c66c3b0832a616"),"accountType" : "Account Type 1","accountGroup" : [
            {
                    "_id" : ObjectId("60d2db5a90c66c3b0832a619"),"accountGroupName" : "Account 1","rangeFrom" : 25,"rangeto" : 35
            },{
                    "_id" : ObjectId("60d3fbfbc1502c3ed8cadf86"),"accountGroupName" : "Account2","rangeFrom" : 850,"rangeto" : 2000
            },{
                    "_id" : ObjectId("60d2ddb1396dbf384898fbad"),"accountGroupName" : "account 1 sample 3","rangeFrom" : 10,"rangeto" : 15
            }
    ],}
    {
    "_id" : ObjectId("60d2db4e90c66c3b0832a617"),"accountType" : "Account Type 2","accountGroup" : [
            {
                    "_id" : ObjectId("60d2e9586c4fa82310349c7c"),"accountGroupName" : "account 2 sample 5","rangeFrom" : 50,"rangeto" : 60
            }
    ]
    }

解决方法

您可以像这样将 position operator $ 用于投影:

YourModel.find({
  "accountGroup.accountGroupName": "Account 1"
},{
  "accountGroup.$": 1
})

示例here

请注意,您正在获取整个文档,因为使用

YourModel.find({"accountGroup.accountGroupName": "Account 1"})

您告诉 mongo“给我一个文档,其中 accountGroupName 数组中的值 accountGroup 等于 Account 1。匹配该条件的文档包含整个数组。

所以使用位置运算符,根据它的描述你需要什么:

位置 $ 运算符限制 an 的内容以返回与数组上的查询条件匹配的第一个元素。

这就是为什么通过一个查询获得整个文档,而通过另一个查询获得您想要的值。

还要注意 $ 只返回匹配查询的第一个子文档。