返回每个Mongo IN查询的唯一文档

问题描述 投票:1回答:1

我在查询一个 Collection 拥有35万+的 Documents. 我在查询一个 field 使用 IN 句中 IN 是一个27k+字段的数组。

实际上,这在 Mongoose. 然而,在 "中国制造 "的每一个项目中,有一些匹配的项目。IN 可以有多个 Documents 与它们相关联。我希望每次匹配只返回1个文档(由另一个字段排序)。这可能吗?

例如,我想在每个匹配中只返回1个文档(按其他字段排序)。比如说我有一个 Collection 的水果。

[
 {type:'apple', price:10},{type:'apple', price:5},{type:'apple', price:3},
 {type:'orange', price:2},
 {type:'pear', price:12}, {type:'pear', price:2}
]

所以,目前我有

const types = ['apple', 'orange', 'pear'];

//Will return full example above
//Returns 12k Docs in real app but bc multiple Docs are returned per item in IN

Fruit.find({type: { $in: types }}, (err, results) => {
        if (err) return console.error(err);
        console.log(results);
});

我只想拥有

 [
         {type:'apple', price:10}
         {type:'orange', price:2},
         {type:'pear', price:12}
    ]

如何调整我的查询做这样的事情?谢谢!返回。所以,不是所有符合类型的文档--我只得到1个价格最高的文档。

javascript mongodb mongoose
1个回答
1
投票

你需要 $组type 并使用 $max 以获得最高价格。

db.collection.aggregate([
    {
        $match: { type: { $in: ['apple', 'orange', 'pear'] } }
    },
    {
        $group: {
            _id: "$type",
            price: { $max: "$price" }
        }
    },
    {
        $project: {
            type: "$_id",
            _id: 0,
            price: 1
        }
    }
])

艋舺游乐场

© www.soinside.com 2019 - 2024. All rights reserved.