我可以在 mongodb 的 $match 聚合函数中使用 $in
Can I use $in within mongodb's $match aggregate function
我正在尝试在 $match(聚合)函数中使用 $in 运算符。出于某种原因,它在“_Id”字段上不起作用,但我找不到任何说明 mongodb.
不支持的文档
var ids = ['1', '2', '3', '4']; //an example. I am using real mongo object ids
// this is working fine
Product.find({_id : {$in : ids}})
.exec(function(err, res){
res.json(res);
});
// no results here
Product.aggregate([
{$match : {_id : {$in : ids}}},
{$group : {_id : '$pCode', total : {$sum : '$pWeight'}}])
.exec(function(err, res){
res.json(res);
现在,如果我使用其他字段进行查询,它就可以正常工作,并且我使用 $in 得到了想要的结果。但出于某种原因,这不适用于“_id”字段。
$in
运算符与 $match
.
配合使用效果很好
你的总和在比赛后似乎不正确:
Product.aggregate([
{$match : {_id : {$in : ids}}},
{$group : {_id : '$pCode', total : {$sum : '$pWeight'}}}
]).exec(function(err, res){
res.json(res);
})
如果不是简单地 运行 没有组的查询,看看这是否可行,这样您可以看到它有效,然后处理您的 $group
部分。
尝试使用
const ObjectId = require("mongodb").ObjectID;
然后像这样转换你的数组:
var ids = [ObjectId('5ae6d812e5504726a69fc285'),ObjectId('5b0bcfc254c93a2734d56efb')];
然后进行汇总。
对于使用 ORM 的聚合,您必须显式转换它。
我正在尝试在 $match(聚合)函数中使用 $in 运算符。出于某种原因,它在“_Id”字段上不起作用,但我找不到任何说明 mongodb.
不支持的文档var ids = ['1', '2', '3', '4']; //an example. I am using real mongo object ids
// this is working fine
Product.find({_id : {$in : ids}})
.exec(function(err, res){
res.json(res);
});
// no results here
Product.aggregate([
{$match : {_id : {$in : ids}}},
{$group : {_id : '$pCode', total : {$sum : '$pWeight'}}])
.exec(function(err, res){
res.json(res);
现在,如果我使用其他字段进行查询,它就可以正常工作,并且我使用 $in 得到了想要的结果。但出于某种原因,这不适用于“_id”字段。
$in
运算符与 $match
.
你的总和在比赛后似乎不正确:
Product.aggregate([
{$match : {_id : {$in : ids}}},
{$group : {_id : '$pCode', total : {$sum : '$pWeight'}}}
]).exec(function(err, res){
res.json(res);
})
如果不是简单地 运行 没有组的查询,看看这是否可行,这样您可以看到它有效,然后处理您的 $group
部分。
尝试使用
const ObjectId = require("mongodb").ObjectID;
然后像这样转换你的数组:
var ids = [ObjectId('5ae6d812e5504726a69fc285'),ObjectId('5b0bcfc254c93a2734d56efb')];
然后进行汇总。 对于使用 ORM 的聚合,您必须显式转换它。