Resort NestedArray

Hi.
I’m working on a project where users are saving each other’s articles, and the saved items need to be able to be resort for other users to see.
How do I do this ?
my sample scheme to saves :

{
    "user_id" : "ObjectId",
    "saves" : [
      "saved_itemId",
      "saved_itemId",
      "saved_itemId",
      "saved_itemId",
      "saved_itemId",
      "saved_itemId",
      "...."
    ]
  }

how to update and resort saves key??

Hi @solo_dios,

Here is my attempt:

MongoDB [direct: primary] test> db.coll.findOne()
{
  _id: ObjectId("62263a2651e4f8025cf52597"),
  user_id: 'ObjectId',
  saves: [
    'saved_itemId5',
    'saved_itemId4',
    'saved_itemId2',
    'saved_itemId3',
    'saved_itemId1',
    'saved_itemId6'
  ]
}

Aggregation:

[
  {
    '$unwind': {
      'path': '$saves'
    }
  }, {
    '$sort': {
      'saves': 1
    }
  }, {
    '$group': {
      '_id': '$_id', 
      'saves': {
        '$push': '$saves'
      }
    }
  }, {
    '$merge': {
      'into': 'coll', 
      'on': '_id', 
      'whenMatched': 'merge', 
      'whenNotMatched': 'fail'
    }
  }
]

Result:

MongoDB [direct: primary] test> db.coll.findOne()
{
  _id: ObjectId("62263a2651e4f8025cf52597"),
  user_id: 'ObjectId',
  saves: [
    'saved_itemId1',
    'saved_itemId2',
    'saved_itemId3',
    'saved_itemId4',
    'saved_itemId5',
    'saved_itemId6'
  ]
}

If that’s not what you wanted, then I didn’t understand your question.

Cheers,
Maxime.

No no.
I did not mean to arrange the reading based on desc or asc.
I meant how to update the array.
For example, move item 4 to item 6 so that the others can see the list in the order in which it was made

If you want to insert elements at a given position in the array I would use $position.

You can also check the other array update operators that MongoDB supports. Basically you can manipulate arrays the way you want.

Cheers,
Maxime.

Thanks very very.
mongodb is a nice db

1 Like