2016-02-14 91 views
0

我是新來查詢DBS和特別mongodb.If我運行:的MongoDB通過尋找另一列值獲取對象ID

db.<customers>.find({"contact_name: Anny Hatte"}) 

我得到:

{ 
    "_id" : ObjectId("55f7076079cebe83d0b3cffd"), 
    "company_name" : "Gap", 
    "contact_name" : "Anny Hatte", 
    "email" : "[email protected]" 
} 

我希望得到的值來自此查詢結果的「_id」屬性。我如何實現這一目標?

同樣,如果我有另外一個集合,命名項目,具有下列數據:

{ 
    "_id" : ObjectId("55f7076079cebe83d0b3d009"), 
    "_customer" : ObjectId("55f7076079cebe83d0b3cfda"), 
    "school" : "St. Patrick's" 
} 

這裏,"_customer"領域是客戶收集"_id"(以前的集合)。我希望獲得"_id""_customer""school"字段值,其中"_customer"的items-collection等於"_id"的customers-collection。

我該如何解決這個問題?

回答

1

我希望從此查詢結果中獲得「_id」屬性的值。 我該如何做到這一點?

find()方法返回一個遊標的結果,您可以遍歷和檢索結果集的文件。你可以使用forEach()來做到這一點。

var cursor = db.customers.find({"contact_name: Anny Hatte"}); 
cursor.forEach(function(customer){ 
//access all the attributes of the document here 
var id = customer._id; 
}) 

你可以利用聚合管道的已被引入的3.2部分$lookup階段,查找並獲取匹配的行中的其他一些相關的集合。

db.customers.aggregate([ 
{$match:{"contact_name":"Anny Hatte"}}, 
{$lookup:{ 
    "from":"items", 
    "localField":"_id", 
    "foreignField":"_customer", 
    "as":"items" 
}} 
]) 

如果您正在使用其中不支持階段的MongoDB以前的版本,那麼,你就需要觸發一個額外的查詢來查找項集合,爲每一個客戶。

db.customers.find(
    {"contact_name":"Anny Hatte"}).map(function(customer){ 
    customer["items"] = []; 
    db.items.find({"_customer":customer._id}).forEach(function(item){ 
    customer.items.push(item); 
    }) 
    return customer; 
})