sql >> Database teknologi >  >> NoSQL >> MongoDB

Find Distinct Embedded Document og gør yderligere distinkt ved hjælp af Field

Du kan bruge MongoBD-aggregering for at få det ønskede resultat (tag et kig ):

db.health.aggregate([
  {
    $sort: {
      "healths.effDate": 1
    }
  },
  {
    $group: {
      _id: "$healths.healthCd",
      healths: {
        $first: "$healths"
      }
    }
  },
  {
    $replaceRoot: {
      newRoot: "$healths"
    }
  }
])

MongoPlayground

Spring Boot Implementering

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

@SpringBootApplication
public class DemoApplication implements CommandLineRunner {

    @Autowired
    private MongoTemplate mongoTemplate;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {

//      //If your operator is not available inside Aggregation or query is too complex, 
//      //use below code to write MongoDB shell code directly as JSON
//      new AggregationOperation() {
//
//          @Override
//          public Document toDocument(AggregationOperationContext context) {
//              return new Document("$group", 
//                  new Document("_id", "$healths.healthCd")
//                      .append("healths", new Document("$first", "$healths")));
//          }
//          
//      },

        Aggregation agg = Aggregation.newAggregation(
            Aggregation.sort(Direction.ASC, "healths.effDate"),
            Aggregation.group("healths.healthCd").first("healths").as("healths"),           
            Aggregation.replaceRoot("healths")
        );

        AggregationResults<Healths> healths = mongoTemplate.aggregate(agg, 
                mongoTemplate.getCollectionName(Health.class), Healths.class);
        for (Healths health : healths.getMappedResults()) {
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            System.out.println(gson.toJson(health));
        }
    }
}



  1. Mongo kompleks sortering?

  2. Opdaterer Service Stack Redis List

  3. tidsserier og aggregeringsramme (mongo)

  4. Slaget om NoSQL-databaserne - Sammenligning af MongoDB og Cassandra