使用猫鼬获取所有文档数组中对象的不同值
Using mongoose to get the distinct values of an object in array for all documents
我在 nodejs 中使用 Mongoose。所以这里是一个示例 Publisher 模型:
name: String,
books: [{
title: String,
author: {
name: String,
age: Number
}
}]
我想获取所有与正则表达式匹配的不同作者姓名。我是 noSql 的新手,所以也许我只是在做一些愚蠢的事情。我想我想做这样的事情:
Publisher.aggregate([
{$unwind: '$books'},
{$match: {
'books.author.name': new RegExp(req.params.regex)
}},
{$group: {
_id: '$books.author.name'
}},
{$group: {
distinctValues: {$addToSet: '$_id'}
}}
], function(err, result) {
if(err) throw err;
res.json(result);
})
这似乎应该根据:https://dba.stackexchange.com/questions/59661/mongodb-distinct-in-an-array
非常感谢你们提供的任何帮助我的意见。
您没有提供执行此查询时遇到的错误,但您似乎得到了类似:'a group specification must include an _id' 的信息。
您查询的问题在这里:
{$group: {
distinctValues: {$addToSet: '$_id'}
}}
$group 运算符必须包含一个 _id 字段
到目前为止,$group 运算符已经提供了不同的组,这最后一个管道似乎是多余的,下一个对我有用:
Publisher.aggregate([
{$unwind: '$books'},
{$match: {
'books.author.name': new RegExp(req.params.regex)
}},
{$group: {
_id: '$books.author.name'
}}
], function(err, result) {
if(err) throw err;
res.json(result);
})
我在 nodejs 中使用 Mongoose。所以这里是一个示例 Publisher 模型:
name: String,
books: [{
title: String,
author: {
name: String,
age: Number
}
}]
我想获取所有与正则表达式匹配的不同作者姓名。我是 noSql 的新手,所以也许我只是在做一些愚蠢的事情。我想我想做这样的事情:
Publisher.aggregate([
{$unwind: '$books'},
{$match: {
'books.author.name': new RegExp(req.params.regex)
}},
{$group: {
_id: '$books.author.name'
}},
{$group: {
distinctValues: {$addToSet: '$_id'}
}}
], function(err, result) {
if(err) throw err;
res.json(result);
})
这似乎应该根据:https://dba.stackexchange.com/questions/59661/mongodb-distinct-in-an-array
非常感谢你们提供的任何帮助我的意见。
您没有提供执行此查询时遇到的错误,但您似乎得到了类似:'a group specification must include an _id' 的信息。 您查询的问题在这里:
{$group: {
distinctValues: {$addToSet: '$_id'}
}}
$group 运算符必须包含一个 _id 字段
到目前为止,$group 运算符已经提供了不同的组,这最后一个管道似乎是多余的,下一个对我有用:
Publisher.aggregate([
{$unwind: '$books'},
{$match: {
'books.author.name': new RegExp(req.params.regex)
}},
{$group: {
_id: '$books.author.name'
}}
], function(err, result) {
if(err) throw err;
res.json(result);
})