2017-06-09 214 views
0

我需要挑选< = 4名的员工谁拥有丰富的经验3-9和工资的总和应小于或等于20万,从以下数据MongoDB的查询组结果

{ 
    "_id" : ObjectId("593a311650692f17327f9db3"), 
    "name" : "Anderson Heidenreich", 
    "experience" : 6, 
    "expected_salary" : 36252 
} 
{ 
    "_id" : ObjectId("593a311650692f17327f9db4"), 
    "name" : "Dr. Collin Stanton IV", 
    "experience" : 8, 
    "expected_salary" : 56000 
} 
{ 
    "_id" : ObjectId("593a311650692f17327f9db5"), 
    "name" : "Zita Von", 
    "experience" : 2, 
    "expected_salary" : 41792 
} 
{ 
    "_id" : ObjectId("593a311650692f17327f9db6"), 
    "name" : "Gregory Reilly", 
    "experience" : 7, 
    "expected_salary" : 77000 
} 
{ 
    "_id" : ObjectId("593a311650692f17327f9db7"), 
    "name" : "Prof. Myles Hackett", 
    "experience" : 3, 
    "expected_salary" : 49133 
} 
{ 
    "_id" : ObjectId("593a311650692f17327f9db8"), 
    "name" : "Janelle Thiel", 
    "experience" : 4, 
    "expected_salary" : 78795 
} 
{ 
    "_id" : ObjectId("593a311650692f17327f9db9"), 
    "name" : "Dr. Elsie Lang", 
    "experience" : 2, 
    "expected_salary" : 99135 
} 
{ 
    "_id" : ObjectId("593a311650692f17327f9dba"), 
    "name" : "Sean Braun", 
    "experience" : 2, 
    "expected_salary" : 63608 
} 
{ 
    "_id" : ObjectId("593a311650692f17327f9dbb"), 
    "name" : "Murray Simonis", 
    "experience" : 7, 
    "expected_salary" : 66000 
} 

预期输出像

{ 
    "_id" : ObjectId("593a311650692f17327f9db4"), 
    "name" : "Dr. Collin Stanton IV", 
    "experience" : 8, 
    "expected_salary" : 56000 
} 
{ 
    "_id" : ObjectId("593a311650692f17327f9db6"), 
    "name" : "Gregory Reilly", 
    "experience" : 7, 
    "expected_salary" : 7700 
} 
{ 
    "_id" : ObjectId("593a311650692f17327f9dbb"), 
    "name" : "Murray Simonis", 
    "experience" : 7, 
    "expected_salary" : 66000 
} 

你能告诉我如何处理mongodb查询吗?

谢谢

回答

0

我做的经验,一个简单的查找查询范围,然后通过工资对结果进行排序,并将结果限制为仅4

db.stack.find({ "experience": {$gt: 3, $lt: 9} }).sort({"expected_salary" : -1 }).limit(4) 

这一操作将输出以下结果:

{ "_id" : ObjectId("593a311650692f17327f9db8"), "name" : "Janelle Thiel", "experience" : 4, "expected_salary" : 78795 } 
{ "_id" : ObjectId("593a311650692f17327f9db6"), "name" : "Gregory Reilly", "experience" : 7, "expected_salary" : 77000 } 
{ "_id" : ObjectId("593a311650692f17327f9dbb"), "name" : "Murray Simonis", "experience" : 7, "expected_salary" : 66000 } 
{ "_id" : ObjectId("593a311650692f17327f9db4"), "name" : "Dr. Collin Stanton IV", "experience" : 8, "expected_salary" : 56000 } 

现在我们的客户端,我们可以只是循环尽管这个结果,直到我们有期望值

我们使用了一些MongoDB的查询操作符(https://docs.mongodb.com/manual/reference/operator/query/

$gt: - 大于 $lt: - 不到

+0

的问题询问了*和*'expected_salary'的小于200K。我想用记录的限制,你可以通过获得四条记录并弹出一条记录,直到总和要求满足为止。 –

+0

一般而言,您要求https://docs.mongodb.com/manual/reference/operator/aggregation/group/,但您无法对聚合进行条件。所以我坚持凯文关于问题的第一部分的想法,并提出了解决方案,并在总结方面对结果进行处理。 –

+0

错过了这个问题,而不是我的'expected_salary'查询,'.sort({“expected_salary”:-1})。limit(4)'取得结果并在应用程序端总结出来最终结果。 –