2017-06-09 159 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)'取得結果並在應用程序端總結出來最終結果。 –