Reputation: 597
I have upgraded Mongo to 3.2 and am delighted that aggregating using $slice works. However, my problem is that I want to assign the value to an object not an array. I cannot find how to do this.
My script applied:
db.std_sourceBusinessData.aggregate(
{ $match : {objectType: "Account Balances"}},
{ $project: {_id: 1,entity_id: 1,accountBalances: 1}},
{ $unwind: "$accountBalances" },
{ $match: {"accountBalances": "Sales"}},
{$project: {
_id :1,
"Value" : {$slice: ["$accountBalances",1,1]},
"key" : {$literal: "sales"},
"company": "$entity_id"
}}
)
Comes back with:
{
"_id" : ObjectId("566f3da3d58419e8b0fc76c7"),
"Value" : [
"5428.64"
],
"key" : "sales"
}
Notice that Value is an array. What I want is:
{
"_id" : ObjectId("566f3da3d58419e8b0fc76c7"),
"Value" : "5428.64",
"key" : "sales"
}
Thanks, Matt
Upvotes: 1
Views: 1585
Reputation: 311865
You can use $arrayElemAt
instead of $slice
to directly get a single array element.
Modify your final $project
stage to be:
{$project: {
_id: 1,
"Value": {$arrayElemAt: ["$accountBalances", 1]},
"key": {$literal: "sales"},
"company": "$entity_id"
}}
Upvotes: 4