1

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

1
  • add an unwind on Value to aggregation - {$unwind: '$Value'} Commented Dec 15, 2015 at 4:17

1 Answer 1

4

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"
}}
Sign up to request clarification or add additional context in comments.

3 Comments

That is great Johnny, awesome. That works, one small problem I have just noticed, the "company": "$entity_id" isn't showing. It is in the origin document, is there something I'm missing in here to retrieve values from the origin document directly? Thanks
You're including entity_id in your initial $project so that should work fine. Comment out the later pipeline stages and see where it's getting lost. If you're still stuck, post a new question as it's unrelated to this one.
cool, thanks, I worked out that the first one has ID instead of id, cases sensitivity issue, thanks, Matt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.