MongoDB的使用索引数组工作
问题描述:
例如,我有一个集合“测试”与阵列场“数字”的指标,我有两个文件有:MongoDB的使用索引数组工作
db.test.createIndex({"numbers": 1})
db.test.insert({"title": "A", "numbers": [1,4,9]})
db.test.insert({"title": "B", "numbers": [2,3,7]})
1)我怎样才能得到所有结果按“数字”(使用索引)排序,因此对于数组中的每个值,我会得到一个完整的文档?就像这样:
{"_id": "...", "title": "A", "numbers": [1,4,9]}
{"_id": "...", "title": "B", "numbers": [2,3,7]}
{"_id": "...", "title": "B", "numbers": [2,3,7]}
{"_id": "...", "title": "A", "numbers": [1,4,9]}
{"_id": "...", "title": "B", "numbers": [2,3,7]}
{"_id": "...", "title": "A", "numbers": [1,4,9]}
2)我怎样才能得到这样的结果(对不起,没有解释,但我想很明显我想要在这里实现):
{"_id": "...", "title": "A", "numbers": 1}
{"_id": "...", "title": "B", "numbers": 2}
{"_id": "...", "title": "B", "numbers": 3}
{"_id": "...", "title": "A", "numbers": 4}
{"_id": "...", "title": "B", "numbers": 7}
{"_id": "...", "title": "A", "numbers": 9}
3 )我怎样才能得到类似的结果,但每个阵列?:
{"_id": "...", "title": "B", "numbers": 3}
{"_id": "...", "title": "A", "numbers": 4}
我也关心PERFO在由第二牙齿订购性能,所以如果你解释哪种技术更快/更慢(当然,如果有多种方法可以做到这一点),它会很棒。谢谢。
UPD:让我澄清。我们有一个关于“数字”数组的索引。所以我想从最小值到最大值迭代这个索引并获得当前值所属的文档。因此,一些文档将在N次结果中呈现,其中N =其数组中的元素数(本例中为“数字”)。
答
通过"dot notation"使用时只需在排序的指标:
db.collection.find().sort({ "numbers.0": 1 })
这是,如果你现在该你想要的位置,所以才用“指数”以最快的方式(起始于0
课程)。所以这同样适用于数组的任何索引位置。
如果你想在阵列中的“最小”值进行排序,那么需要更多的工作,使用.aggregate()
工作了这一点:
db.collection.aggregate([
{ "$unwind": "$numbers" },
{ "$group": {
"_id": "$_id",
"numbers": { "$push": "$numbers" },
"min": { "$min": "$numbers" }
}},
{ "$sort": { "min": 1 } }
])
,自然是要采取执行更多的时间由于完成的工作比以前的形式。当然,要求$unwind
为了将数组元素去归一化为单个文档,并且要求$group
具体为$min
以找到最小值。那当然有你需要的基本$sort
。
对于整个事情,那么你基本上可以做到这一点:
db.test.aggregate([
{ "$project": {
"title": 1,
"numbers": 1,
"copy": "$numbers"
}},
{ "$unwind": "$copy" },
{ "$group": {
"_id": {
"_id": "$_id",
"number": "$copy"
},
"numbers": { "$first": "$numbers" }
}},
{ "$sort": { "_id.number": 1 } }
])
主要生产:
{
"_id" : {
"_id" : ObjectId("560545d64d64216d6de78edb"),
"number" : 1
},
"numbers" : [ 1, 4, 9 ]
}
{
"_id" : {
"_id" : ObjectId("560545d74d64216d6de78edc"),
"number" : 2
},
"numbers" : [ 2, 3, 7 ]
}
{
"_id" : {
"_id" : ObjectId("560545d74d64216d6de78edc"),
"number" : 3
},
"numbers" : [ 2, 3, 7 ]
}
{
"_id" : {
"_id" : ObjectId("560545d64d64216d6de78edb"),
"number" : 4
},
"numbers" : [ 1, 4, 9 ]
}
{
"_id" : {
"_id" : ObjectId("560545d74d64216d6de78edc"),
"number" : 7
},
"numbers" : [ 2, 3, 7 ]
}
{
"_id" : {
"_id" : ObjectId("560545d64d64216d6de78edb"),
"number" : 9
},
"numbers" : [ 1, 4, 9 ]
}
您好,感谢您的回答,但您的解决方案并没有做到这一点* *对于数组中的每个值,我会得到一个完整的文档**。我怎么才能得到它? UPD:我想在第一和第二种情况下得到6(6)个结果 –
@ d-d当然是的。按照“索引”进行排序(您的问题标题,尽管存在多个问题 - 请不要再这么做,首先请原谅)不会以任何方式影响文档。至于'。在使用'$ group'或'$ project'等运算符时,使用“aggregate()'方法来定义要返回的字段。像['$ first'](https://docs.mongodb.org/master/reference/operator/aggregation/first/)这样的运算符可以帮助你。阅读一些文档,不要对那些知识多于自己的人在你需要帮助时做出“不起作用”的匆忙评论。 –
@ d-d和**对于数组中的每个值**(我也可以喊)然后只需使用'$ unwind'而不用'$ group'并对值进行排序。如果你花费了超过两秒的时间实际阅读你刚才给出的有用信息,那就相当简单。 –