Mat*_*urn 3 slice mongodb mongodb-query aggregation-framework
我想从嵌套数组中检索一个值,它存在于数组中的确切位置.
我想通过做$片[0,1]为创建名称值对的名称,然后$片[1,1]的值.
在我尝试使用聚合之前,我想在嵌套数组中尝试查找.我可以在文档中的单个深度数组上执行我想要的操作,如下所示:
{
"_id" : ObjectId("565cc5261506995581569439"),
"a" : [
4,
2,
8,
71,
21
]
}
Run Code Online (Sandbox Code Playgroud)
我应用以下内容:db.getCollection('anothertest').find({},{_ id:0,a:{$ slice:[0,1]}}) 我得到:
{
"a" : [
4
]
}
Run Code Online (Sandbox Code Playgroud)
这是太棒了.但是,如果我想要$ slice [0,1]的数组位于objectRawOriginData.Reports.Rows.Rows.Cells的文档中呢?
如果我可以首先找到FIND,那么我想将其应用为AGGREGATE.
Bla*_*ven 10
在这里你最好的选择,特别是如果你的应用程序还没有准备好发布,那就是推迟到MongoDB 3.2进行部署,或者至少在此期间开始与候选版本合作.主要原因是"投影" $slice不适用于聚合框架,因为其他形式的数组匹配投影也不适用.但这已经针对即将发布的版本进行了解决.
这将为您提供几个新的运算符,$slice甚至$arrayElemAt可以用于通过聚合管道中的位置来寻址数组元素.
或者:
db.getCollection('anothertest').aggregate([
{ "$project": {
"_id": 0,
"a": { "$slice": ["$a",0,1] }
}}
])
Run Code Online (Sandbox Code Playgroud)
返回熟悉的:
{ "a" : [ 4 ] }
Run Code Online (Sandbox Code Playgroud)
要么:
db.getCollection('anothertest').aggregate([
{ "$project": {
"_id": 0,
"a": { "$arrayElemAt": ["$a", 0] }
}}
])
Run Code Online (Sandbox Code Playgroud)
这只是元素而不是数组:
{ "a" : 4 }
Run Code Online (Sandbox Code Playgroud)
除了发布候选表单之外的那个版本可用之外,当前可用的运算符使得数组的"first"元素变得非常容易:
db.getCollection('anothertest').aggregate([
{ "$unwind": "$a" },
{ "$group": {
"_id": "$_id",
"a": { "$first": "$a" }
}}
])
Run Code Online (Sandbox Code Playgroud)
通过使用后的$first操作员$unwind.但是获得另一个索引位置变得非常迭代:
db.getCollection('anothertest').aggregate([
{ "$unwind": "$a" },
// Keeps the first element
{ "$group": {
"_id": "$_id",
"first": { "$first": "$a" },
"a": { "$push": "$a" }
}},
{ "$unwind": "$a" },
// Removes the first element
{ "$redact": {
"$cond": {
"if": { "$ne": [ "$first", "$a" ] },
"then": "$$KEEP",
"else": "$$PRUNE"
}
}},
// Top is now the second element
{ "$group": {
"_id": "$_id",
"second": { "$first": "$a" }
}}
])
Run Code Online (Sandbox Code Playgroud)
等等,还有很多处理来改变它来处理可能比你正在寻找的"第n"元素更短的数组.所以"可能",但丑陋而且不具备表现力.
同时注意到"并非真正"使用"索引位置",并且纯粹与值匹配.因此,除非每个数组元素都有另一个唯一标识符,否则很容易删除重复的值.Future $unwind还具有投影数组索引的能力,这对于其他目的而言非常方便,但其他运算符对于此特定情况比该功能更有用.
所以对于我的钱,我会等到你有这个功能可以将它集成到聚合管道中,或者至少重新考虑为什么你认为你需要它并可能围绕它进行设计.