我有一个像下面这样的示例数据,我只想使用包含Volvo
的数据来提取结果。
[
'Volvo Sedan',
'Volvo SUV',
'Volvo Premium',
'Volvo Sport',
'Honda Sedan',
'Honda SUV',
'Honda Premium',
'Honda Sport'
]
我尝试过类似的操作,但未返回任何结果。有人可以指导如何实现吗?
db.cars.distinct('carType', {carType: {$in: [/Volvo/]}})
首先$in用于将文档中字段的值与查询中的项目数组进行比较,而不是其他方式。例如。选择具有至少一个与carType
匹配的/Volvo/
的所有文档就足够了
db.cars.distinct('carType', {carType: /Volvo/})
第二,distinct处理文档。首先,它将过滤器应用于在carType数组中具有至少一个 Volvo的文档,然后在这些文档中获取all carType并合并为具有唯一值的单个数组。例如。如果您有带有carTypes的文档
[
'Volvo Sedan',
'Volvo SUV',
'Volvo Premium',
'Volvo Sport',
'Honda Sedan',
'Honda SUV',
'Honda Premium',
'Honda Sport'
]
第一项与/ Volvo /匹配,因此所有这些都将包含在结果中。
假设您要检索具有与正则表达式匹配的唯一carType的列表,则需要使用聚合框架。例如:
db.cars.aggregate([
{$unwind: "$carType"},
{$match: {carType: /Volvo/}},
{$group: {_id: "$carType"}}
])