相关疑难解决方法(0)

仅检索MongoDB集合中对象数组中的查询元素

假设我的收藏中有以下文件:

{  
   "_id":ObjectId("562e7c594c12942f08fe4192"),
   "shapes":[  
      {  
         "shape":"square",
         "color":"blue"
      },
      {  
         "shape":"circle",
         "color":"red"
      }
   ]
},
{  
   "_id":ObjectId("562e7c594c12942f08fe4193"),
   "shapes":[  
      {  
         "shape":"square",
         "color":"black"
      },
      {  
         "shape":"circle",
         "color":"green"
      }
   ]
}
Run Code Online (Sandbox Code Playgroud)

查询:

db.test.find({"shapes.color": "red"}, {"shapes.color": 1})
Run Code Online (Sandbox Code Playgroud)

要么

db.test.find({shapes: {"$elemMatch": {color: "red"}}}, {"shapes.color": 1})
Run Code Online (Sandbox Code Playgroud)

返回匹配的文档(文档1),但始终包含所有数组项shapes:

{ "shapes": 
  [
    {"shape": "square", "color": "blue"},
    {"shape": "circle", "color": "red"}
  ] 
}
Run Code Online (Sandbox Code Playgroud)

但是,我想仅使用包含以下内容的数组来获取文档(文档1)color=red:

{ "shapes": 
  [
    {"shape": "circle", "color": "red"}
  ] 
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

projection mongodb mongodb-query aggregation-framework

356
推荐指数
11
解决办法
26万
查看次数

MongoDB嵌入式vs数组子文档性能

鉴于以下竞争模式与多达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"
    }
}
}
Run Code Online (Sandbox Code Playgroud)

Doc2(user_id和friends.id上的复合多键索引)

{
"_id" : "…",
"user_id" : "1",
friends : [
   {
        "id" : "2",
        "mutuals" : 3
    },
    {
         "id" : "3",
         "mutuals": "1"
    },
   {
         "id" : "4",
         "mutuals": "5"
    }
]}
Run Code Online (Sandbox Code Playgroud)

我似乎无法找到有关子字段检索效率的任何信息.我知道mongo在内部将数据实现为BSON,所以我想知道这是否意味着投影查找是二进制O(log n)?

具体来说,给定user_id以查找是否存在具有friend_id的朋友,每个模式上的两个不同查询将如何比较?(假设上面的索引)请注意,返回的内容并不重要,只有在朋友存在时才返回非null.

Doc1col.find({user_id …
Run Code Online (Sandbox Code Playgroud)

arrays mongodb nosql

12
推荐指数
1
解决办法
7149
查看次数