Home > OS >  How can I add a new Field (key with value) below another Field (key with value)?
How can I add a new Field (key with value) below another Field (key with value)?

Time:07-19

Hello I am trying to set a new key below or above another key (field) just to make the documents a little more organized but when I try to use $addField or $set in Aggregations in MongoDB Compass it adds the new key at the end of the document, for example: I want to add the key "amazing" above the key "something" with value "0", I use that:

{
  "name": "$name",
  "city": "$city",
  "amazing": "0",
  "something": "$something",
  "something2": "$something2",
}

but when I try to do that the preview of the compass shows me that the key "amazing" will be added but at the end of the document, below "something2".

If there is a way to do that in Java it would be cool too, please, thanks in advance.

CodePudding user response:

As @Takis mentioned with the answer here, you can use projections to specify the fields and the order of them. I verified it works very well in Mongosh.

As for java implementation, you may refer to this post which has a an example to help you.

https://www.mongodb.com/docs/drivers/java/sync/current/fundamentals/builders/projections/

Code snippet:

Bson filter = Filters.empty();
Bson projection = include("year", "type");
collection.find(filter).projection(projection).forEach(doc -> System.out.println(doc.toJson()));

CodePudding user response:

By looking at https://www.mongodb.com/docs/manual/reference/operator/aggregation/addFields/ documentation $addFields its meant to add the new fileds and return it in the last position in the result. One method of getting the result you expect is to rearrange the code so that the files are placed in that particular order. Or you can return the result using a Sorting system, such as using an alphabetical Sorting system. (Also if hashmap order its not revelant to the project)

  • Related