我在一个MongoDB DB中有这个示例users条目:
{
_id: xxx,
name: "name",
files:[{
fileName: "test",
size: 654
},
{fileName: "test2",
size: 50
}]
}我使用Pymongo查询名为“test”的文件:
users.find_one({'files.filename':"test"})
如何限制Pymongo的输出,从而只给出包含"test“的dict?换句话说,我希望它输出以下内容:
{
fileName: "test",
size: 654
}发布于 2022-09-25 15:56:19
有一种方法你可以做到。
db.users.aggregate([
{
"$match": {
"files.fileName": "test"
}
},
{
"$replaceWith": {
"$first": {
"$filter": {
"input": "$files",
"as": "file",
"cond": {
"$eq": ["$$file.fileName", "test"]
}
}
}
}
}
])在mongoplayground.net上试一试。
https://stackoverflow.com/questions/73845626
复制相似问题