如何删除组的mongodb中的最小值? [英] How remove min value in mongodb for group?

查看:69
本文介绍了如何删除组的mongodb中的最小值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是mongodb的初学者.

I am beginner with mongodb.

我需要删除每家商店的最低价格.

I need to remove min price for each store.

文档(产品):

输入:

product_id|store_id|price|color|
--------------------------------
1         |   1    | 10  |red
2         |   1    | 9   |blue
3         |   1    | 12  |red
4         |   2    | 19  |red
5         |   2    | 20  |red
6         |   2    | -1  |red
7         |   6    | 30  |red
8         |   6    | 10  |blue

输出:

product_id|store_id|price|color|
--------------------------------
2         |   1    | 9   |blue
3         |   1    | 12  |red
4         |   2    | 19  |red
5         |   2    | 20  |red
8         |   6    | 10  |blue

我在my.js中编写这段代码

I write this code in my.js

use stores;
var products=db.products.distinct('product_id');
for(i=0; i<products.length; i++){
   db.products.remove({product_id:i,color:'red'}).sort({price:1}).limit(1);
}

但是我的代码不起作用,请编写更好的代码或显示我的错误/

But my code not works,Please write better code or show my mistake/

谢谢

推荐答案

您可能想尝试:

// this returns an array of documents which has the store_id and the minimum price for that store
myresult = db.products.aggregate( [ 
                            { $group: 
                                 { _id: "$store_id", 
                                   price: { $min: "$price" } 
                                 } 
                            } 
                            ] ).result

// loop through the results to remove the documents matching the the store id and price

for (i in myresult) { 
    db.products.remove( 
         { store_id: myresult[i]._id, price: myresult[i].price } 
    ); 
}

这篇关于如何删除组的mongodb中的最小值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆