2011-12-19 49 views
0

好奇 - 在下面的例子中,爲什麼mongo REPL不會將用戶散列存儲在變量'a'之後的第一個打印?Mongo REPL將結果存儲在var?

這與mongo的懶惰查詢評估有什麼關係嗎?

> var a = db.users.find(0) 
> a 
{ "_id" : ObjectId("4eed6dc299cd67e275000001"), "provider" : "facebook", "uid" : "343323487", "name" : "Brian Jordan", "email" : "[email protected]" } 
> a 
> 

回答

2

您可以使用findOne

> var a = db.testcoll.findOne() 
> a 
{ 
    "_id" : ObjectId("4e7930a3ff647405d6000003"), 
    "bf" : false, 
    "df" : ISODate("2011-09-21T00:32:35.629Z") 
} 

或者你可以看它的源和做同樣的事情

> db.testcoll.findOne 
function (query, fields) { 
    var cursor = this._mongo.find(this._fullName, this._massageObject(query) || {}, fields, -1, 0, 0, 0); 
    if (!cursor.hasNext()) { 
     return null; 
    } 
    var ret = cursor.next(); 
    if (cursor.hasNext()) { 
     throw "findOne has more than 1 result!"; 
    } 
    if (ret.$err) { 
     throw "error " + tojson(ret); 
    } 
    return ret; 
}