node.js - MONGOOSE - 仅返回匹配数组过滤器的对象
问题描述
我在 mongoDB 中有一个这样的数据结构
{_id:ObjectId(''),
"awards" : [
{
"award" : "Ballon d'Or",
"numberOfTimes" : 6
},
{
"award" : "Golden Boot",
"numberOfTimes" : 6
},
{
"award" : "FIFA World Player of the Year",
"numberOfTimes" : 1
}
],
push:true
}
我目前正在使用这个月光过滤器{'awards.award':"Ballon d'Or"}
我只想在奖项数组中返回与金球奖相匹配的对象
所以输出看起来像这样
{_id:ObjectId(''),
"awards" : [
{
"award" : "Ballon d'Or",
"numberOfTimes" : 6
}
],
push:true
}
谢谢
解决方案
您可以projection operator '$'
为此使用:
你可以试试:
db.collection.find({'awards.award':"Ballon d'Or"}, {'awards.$' : 1})
awards.$:1
只会从奖项数组中返回匹配的对象。
注意: $(projection)
运算符仅返回数组的第一个匹配元素
备用:
如果你想要所有匹配的元素,你可以使用聚合管道。您将需要首先展开奖励数组,应用过滤器以仅获得所需的结果,然后再次将它们分组以获取数组。
试试这个聚合管道:
db.collection.aggregate([
{
"$unwind": "$awards"
},
{
$match: {
"awards.award": "Ballon d'Or"
}
},
{
$group: {
_id: "$_id",
push: {
$first: "$push"
},
awards: {
$push: "$awards"
}
}
}
])
看看这个MongoDB Playground来玩聚合管道。
推荐阅读
- javascript - JSON.parse().replace() 提供与 str.replace() 不同的结果
- java - 如何在 Java 流的 Lambda 表达式中使用反射?
- python - 如何识别 Python 中是否至少有一个大写字母?
- python - 继承和 __init__
- c# - 是否可以设置 dotnet watch run 以替换更改的 DLL 而无需重新启动整个过程?
- python - 一定范围内的随机列表
- c++ - 我如何编写一个程序来计算与我输入的另一个数字不同的数字的数字的乘积?
- python - 在 Python 中动态构建 json
- ios - 我如何知道/获取我的 iOS 应用程序支持的方向列表?
- r - 摘要格式