![](/img/trans.png)
[英]How to push an existing sub-document into an embedded array in MongoDB?
[英]MongoDB embedded vs array sub document performance
鑒於以下競爭模式與多達100,000個朋友,我有興趣找到最有效的我的需求。
Doc1(user_id索引)
{
"_id" : "…",
"user_id" : "1",
friends : {
"2" : {
"id" : "2",
"mutuals" : 3
}
"3" : {
"id" : "3",
"mutuals": "1"
}
"4" : {
"id" : "4",
"mutuals": "5"
}
}
}
Doc2(user_id和friends.id上的復合多鍵索引)
{
"_id" : "…",
"user_id" : "1",
friends : [
{
"id" : "2",
"mutuals" : 3
},
{
"id" : "3",
"mutuals": "1"
},
{
"id" : "4",
"mutuals": "5"
}
]}
我似乎無法找到有關子字段檢索效率的任何信息。 我知道mongo在內部將數據實現為BSON,所以我想知道這是否意味着投影查找是二進制O(log n)?
具體來說,給定user_id以查找是否存在具有friend_id的朋友,每個模式上的兩個不同查詢將如何比較? (假設上面的索引)請注意,返回的內容並不重要,只有在朋友存在時才返回非null。
Doc1col.find({user_id : "…"}, {"friends.friend_id"})
Doc2col.find({user_id : "…", "friends.id" : "friend_id"}, {"_id":1})
同樣令人感興趣的是$ set修飾符的工作原理。 對於模式1,給定查詢Doc1col.update({user_id : "…"}, {"$set" : {"friends.friend_id.mutuals" : 5})
,friends.friend_id上的查找如何工作? 這是一個O(log n)操作(其中n是朋友的數量)?
對於模式2,查詢Doc2col.update({user_id : "…", "friends.id" : "friend_id"}, {"$set": {"friends.$.mutuals" : 5})
比較以上的?
如果一個人的主要要求是在一個漂亮的可管理包中向ui提供數據,那么doc1更受歡迎。 使用投影{}, {friends.2 : 1}
只過濾所需數據很簡單
doc2是你最強的匹配,因為你的用例並不關心結果請注意,返回的內容並不重要 ,索引會加快獲取速度。
在那個doc2之上允許更清晰的語法
db.doc2.findOne({user_id: 1, friends.id : 2} )
與
db.doc1.findOne({ $and : [{ user_id: 1 }, { "friends.2" : {$exists: true} }] })
然而,最后一點,人們可以在doc1上創建一個稀疏索引 (並使用$ exists),但你有10萬朋友的可能性 - 每個朋友需要一個稀疏索引 - 這使得這很荒謬。 反對合理數量的條目說人口統計學性別[男性,女性],年齡組[0-10,11-16,25-30,...]或更多的東西[杜松子酒,威士忌,伏特加,......]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.