mongodb - 节点猫鼬嵌入文档数组
问题描述
我在这里有我的示例 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
吗?
先感谢您。
解决方案
根据我的说法, 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"
}
]
}
]
推荐阅读
- excel - 需要查找一个值并在其他两个文本框上显示以下单元格
- python - 如何更改 Django 过滤器中的查询参数?
- angular - 角度升级8到9后ng服务失败
- arrays - 在 laravel foreach 循环中传递多个变量
- vuetify.js - 根据对象属性控制 v-list-item
- docker - Apache Airflow:如何使用来自另一个任务的环境变量运行 Docker Operator?
- python - 我的帕斯卡三角程序中这个神秘数字是从哪里来的?
- javascript - 如何禁用 html 范围滑块?
- indexeddb - svelte.dev/repl 似乎不支持 indexedDb(或 localStorage)
- swift - textField 最大长度和邮政编码验证