如何查询从一系列对象获取特定对象?
目前,我正在学习MongoDB。假设我在mongoDB中有一个名为post的集合:
[{
id: 123,
uId: 111,
msg: 'test 1',
attachments: [
{name: 'attach1', url: 'https://example.com', isDeleted: false},
{name: 'attach2', url: 'https://example.com', isDeleted: true}
]
},
{
id: 456,
uId: 222,
msg: 'test 2',
attachments: [
{name: 'attach1', url: 'https://example.com', isDeleted: true}
]
},
{
id: 789,
uId: 333,
msg: 'test 3',
attachments: [
{name: 'attach1', url: 'https://example.com', isDeleted: false}
]
}]
,我想要所有post的结果。
[{
id: 123,
uId: 111,
msg: 'test 1',
attachments: [
{name: 'attach1', url: 'https://example.com', isDeleted: false}
]
},
{
id: 456,
uId: 222,
msg: 'test 2',
attachments: []
},
{
id: 789,
uId: 333,
msg: 'test 3',
attachments: [
{name: 'attach1', url: 'https://example.com', isDeleted: false}
]
}]
现在 {isDeleted:false}}}})但不起作用。我从[https://stackoverflow.com/questions/62953855/how-get-get-query-for-arre-aray-aray-objects-in-mongodb]获得了帮助。
Currently I am learning mongodb. Suppose I have one collection named post in mongodb which data is :
[{
id: 123,
uId: 111,
msg: 'test 1',
attachments: [
{name: 'attach1', url: 'https://example.com', isDeleted: false},
{name: 'attach2', url: 'https://example.com', isDeleted: true}
]
},
{
id: 456,
uId: 222,
msg: 'test 2',
attachments: [
{name: 'attach1', url: 'https://example.com', isDeleted: true}
]
},
{
id: 789,
uId: 333,
msg: 'test 3',
attachments: [
{name: 'attach1', url: 'https://example.com', isDeleted: false}
]
}]
Now i want the result of all post where attachments.isDeleted is false which look like :
[{
id: 123,
uId: 111,
msg: 'test 1',
attachments: [
{name: 'attach1', url: 'https://example.com', isDeleted: false}
]
},
{
id: 456,
uId: 222,
msg: 'test 2',
attachments: []
},
{
id: 789,
uId: 333,
msg: 'test 3',
attachments: [
{name: 'attach1', url: 'https://example.com', isDeleted: false}
]
}]
I tried this db.post.find({attachments: {$elemMatch: {isDeleted: false}}})
but it is not working. I have taken help from [https://stackoverflow.com/questions/62953855/how-get-query-for-array-of-objects-in-mongodb]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这就是您要寻找的。它使用MongoDB聚合框架。您可以查看文档以查看详细信息。简而言之,
$ project
阶段允许我们选择字段显示或隐藏,并接受计算的字段。我们使用$ filter
avage 带有给定条件的阶段(iSdeleted
等于false> false
)。您可以尝试: https://mongoplay.net.net.net/p/ydvpkbziz2h
请注意,我更改了<请注意<请注意<请注意<代码> id _id ,但仅适用于样式 目的。
希望我帮忙。
I think this is what you are looking for. It uses the Mongodb aggregation framework. You can take a look the documentation to see details. In brief, the
$project
stage allow us select fields to show or to hide, and it admits calculated fields. We calculated a newattachments
field using$filter
stage with a the given condition (isDeleted
equals tofalse
).You can try it in: https://mongoplayground.net/p/YDvpkbZIZ2H
Note that I changed
id
by_id
, but it was only for style purpose.Hope I helped.