Search code examples
mongodbmongodb-java

How to Transform mongodb query using java code


I am new to MongoDB. I wanted to transform this mongo DB query to java code. I have tried a little bit. But I am having an issue. Please, If anybody helps means that will be a great help for me. Thanks in advance.

db.getCollection('test').aggregate(
  [{
      $match: {
        "ids": 9999999,
        $or : [{"tags.name":"roja"},{"tags.location":"US"},{"tags.year":2019}]
      }
    },
    {
      '$facet': {
        metadata: [{ $count: "total" }],
        data: [{
          $addFields: {
            "weight": {
              $map: {
                input: "$tags",
                as: "tagsEl",
                in: {
                  "$add": 
                    [              
                      {$cond: [ { $eq: [ '$$tagsEl.roja', 'roja' ] }, 15, 1 ]} ,
                      {$cond: [ { $eq: [ '$$tagsEl.location', 'US' ] }, 10, 1 ]},
                      {$cond: [ { $eq: [ '$$tagsEl.year', 2019 ] }, 5, 1 ]}                    
                    ]
                }
              }
            }
          }
        }, { $skip: 0 }, { $limit: 10 }, { '$sort': { 'weight' : -1 } }]
      }
    }
  ]
)

Solution

  • You can use Studio3T to directly convert your query into java code, unless you don't get comfortable with the syntax.

    https://studio3t.com/knowledge-base/articles/query-code/