簡體   English   中英

將mongo db查詢減少為純數組

[英]reduce mongo db query to pure array

當我運行db.abhishek.em.find({})我有

{ "_id" : ObjectId("5ac62d35b075e574b3e7eeaa"), "name" : "first", "employed" : true }
{ "_id" : ObjectId("5ac62d3fb075e574b3e7eeab"), "name" : "second", "employed" : true }
{ "_id" : ObjectId("5ac62d4eb075e574b3e7eeac"), "name" : "third", "employed" : false }

我想通過添加或鏈接某些東西來查找函數來將結果簡化為一個簡單的對象ID數組,例如db.abfind({employed:true})。somefunction()這樣的函數,它可以返回以下我想使用的數組在較大的查詢中嵌套有$ in的命令以實現某種關系查詢

[
ObjectId("5ac62d35b075e574b3e7eeaa"),
ObjectId("5ac62d3fb075e574b3e7eeab")
]

- - - - - - - - -編輯 - - - - - - - - - - -

舉個例子,我想通過跑步來獲得受雇的員工

db.abhishek.another.find({id:{$in:db.abhishek.em.find({employed:true},{_id:1}).toArray()}})

或類似的東西,因為此命令不起作用

db.a.另一個集合是

{ "_id" : ObjectId("5ac63de1b075e574b3e7eead"), "id" : ObjectId("5ac62d35b075e574b3e7eeaa"), "name" : "Lets say person 1" }
{ "_id" : ObjectId("5ac63df7b075e574b3e7eeae"), "id" : ObjectId("5ac62d3fb075e574b3e7eeab"), "name" : "Lets say person 2" }
{ "_id" : ObjectId("5ac63e06b075e574b3e7eeaf"), "id" : ObjectId("5ac62d4eb075e574b3e7eeac"), "name" : "Lets say person 3" }

-----------------編輯----------------------解決了,請看下面的答案

使用MongoDB僅提供模型中的那些字段。 在MongoDB中,這稱為Projection。 您可以將MongoDB方法.project()鏈接到查詢中,如下所示:

db.abhishek.em.find({}).project({});

應該這樣做。 如果要顯式排除字段,請執行以下操作:

db.abhishek.em.find({}).project({name:0, employed:0});

然后,最后以數組形式獲取輸出:

db.abhishek.em.find({}).project({name:0, employed:0}).toArray();

參考在這里:

https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/

感謝大家提供前進的方向和建議,我能夠使用以下命令成功進行某種基於關系的查詢

db.abhishek.another.find({id:{$in:db.abhishek.em.find({employed:true},{_id:1}).map(function(e) {return e._id})}},{name:1,_id:0})

它將此作為輸出

{ "name" : "Lets say person 1" }
{ "name" : "Lets say person 2" }

該查詢從em集合中獲取了所有記錄,並將employee set設置為true,形成其數組,然后將其傳遞給查詢“另一個”集合的$ in運算符以提供輸出

toArray方法用於轉換嵌套在數組中的對象,因此$ in運算符失敗

感謝@veeram講述了字段選擇

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM