Home > Software engineering >  Move "property: value" position in MongoDB
Move "property: value" position in MongoDB

Time:07-18

I've been wondering if you could move one field position. For example:

Current Document:

{
    user_id: 1234567890,
    coins: 100,
    card: 500,
    username: 'Shin'
}

(Expected Document) I would like to move the username into this:

{
    user_id: 1234567890,
    username: 'Shin',
    coins: 100,
    card: 500
}

CodePudding user response:

Query

  • as far as i know project keeps the order we define
  • but try it on your driver to be sure, with more fields also
  • the problem is that we have to do this for all fields (here are only 4 so its ok)
  • but why you need that? in general because its hash-map we dont care about the order

Playmongo

aggregate(
[{"$project": 
   {"user_id": "$user_id",
    "username": "$username",
    "coins": "$coins",
    "card": "$card"}}])
  • Related