mongodb - mongoDB 通过 id 查找并返回匹配的子文档
问题描述
我有这个收藏:
{
_id:0,
user_id: 12,
list: [{_.id:0, name:"john"},{_.id:1, name:"hanna"}]
},
{
_id:1,
user_id: 22,
list: [{_.id:0, name:"john"},{_.id:1, name:"hanna"}]
}
我想像这样查询集合:find the document by user_id
and return only {_.id:0, name:"john"}
insidelist
找不到任何线索如何做到这一点
一些示例可以更好地解释我想要实现的目标:
const johnDoc = findOne({user_id:0}).list.findOne({name:"john"})
我知道它不仅对解释我想要达到的目标有效。
解决方案
你可以试试这个$unwind
db.collection.aggregate([
{
$match: {
user_id: 12,
"list.name": "john"
}
},
{
$unwind: "$list"
},
{
$match: {
user_id: 12,
"list.name": "john"
}
},
])
推荐阅读
- ios - 更改项目位置xcode 9.2时如何解决swift编译器错误?
- pycharm - 为什么我无法导入 google-cloud-speech?
- ios - iOS 中的 Facebook 登录 SDK 语言问题
- javascript - 对位于另一个单独范围内的范围进行求和的算法
- python - 需要在 Python 中转换有效日期值并错误输出无效值
- javascript - 对象作为 React 子级无效(找到:[object HTMLDivElement])
- javascript - Angular 6:不能绑定到“formGroup”,因为它不是“form”的已知属性?
- c# - 属性初始化器不能引用非静态字段
- android - Java rx - 你应该使用 Single
- > 或者更确切地说是观察
- c++ - 如何通过 Cppcheck 解释 Null 指针取消引用?