首页 > 解决方案 > 节点猫鼬嵌入文档数组

问题描述

我在这里有我的示例 userSchema:

{
    "_id": objectId("6092076ba811e50b565497ec"),
    "username": "test@gmail.com",
    "address_book": [{
        "_id": objectId("6092b1120f7e370b954a2708"),
        "address": "address1",
        "address2": "address2",
    }, {
        "_id": objectId("6093edcb88796b0a5eba19a3"),
        "address": "test1",
       "address2": "test2",
    }]
}

我可以通过 objectId("6092076ba811e50b565497ec")and找到用户吗address_book._id object("6093edcb88796b0a5eba19a3")

它只返回address_book我选择的那个?我的预期回报数据应该是这样的

{
    "_id": objectId("6092076ba811e50b565497ec"),
    "username": "test@gmail.com",
    "address_book": {
        "_id": objectId("6093edcb88796b0a5eba19a3"),
        "address": "test1",
       "address2": "test2",
    }
}

这是我的示例函数

let user = [];
await User.findOne({
   _id: id,
   "address_book._id": address_id,
 })
.then((result) => {
   console.log(result);
   user = result;
 })
 .catch((err) => console.log(err));
 return user;

有了这个我得到了所有的地址簿

也可以通过 updateOrCreate 函数来实现address_book._id吗?

先感谢您。

标签: mongodbmongoose

解决方案


根据我的说法, elemMatch是您正在寻找的东西。elemMatch 用于投影,而不仅仅是匹配。

    db.<collection name>.find({
  < search using elem match >
}, {
  games: {
    $elemMatch: {
      //put your projection piece here, whatever selective what you want, check the example on documentation
      score: {
        $gt: 5
      }
    }
  },
  //anything else that you would want apart from within array projection
})

更新 :

数据

    [
  {
    "_id": "6092076ba811e50b565497ec",
    "username": "test@gmail.com",
    "address_book": [
      {
        "_id": "6092b1120f7e370b954a2708",
        "address": "address1",
        "address2": "address2",
        
      },
      {
        "_id": "6093edcb88796b0a5eba19a3",
        "address": "test1",
        "address2": "test2",
        
      }
    ]
  }
]

命令

db.collection.find({},
{
  address_book: {
    $elemMatch: {
      address: "test1"
    }
  }
})

结果

[
  {
    "_id": "6092076ba811e50b565497ec",
    "address_book": [
      {
        "_id": "6093edcb88796b0a5eba19a3",
        "address": "test1",
        "address2": "test2"
      }
    ]
  }
]

操场


推荐阅读