[英]mongodb find single embedded document as an object not as an array
我想知道在MongoDB中查詢單個嵌入式文檔時是否有辦法獲取單個對象而不是數組
我有具有嵌入式用戶的 網上論壇
{
groupname: "Admins",
users: [
{
email: bob@google.com,
first_name: 'bob'
},
{...},
{...} // multiple embedded users
]
}
我可以使用此查詢從組中查詢單個用戶
db.groups.find({'users.email' => bob@google.com}, {'users.$' => 1})
但這給了我一個帶有1個用戶init的'users' 數組
{
groupname: "Admins",
users: [
{
email: bob@google.com,
first_name: 'bob'
}
]
}
然后我必須選擇數組中的第一個元素,
users[0]
它沒有問題,但是那我只需要在我的應用程序中編寫更多代碼,更好的方法應該是
user (-s)
所以我可以查詢
user.first_name
如果有人知道讓我知道
You can use findOne as it returns a single document, where find returns a cursor.
>user = db.groups.findOne({'users.email' : bob@google.com}, {'users.$' => 1})
>user.first_name
根據不贊成使用findOne的驅動程序,應使用find()。limit(1).next(function(err,doc){})
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findOne
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.