sql >> Database >  >> NoSQL >> MongoDB

Zoek een apart ingesloten document en maak verder onderscheid met behulp van Field

U kunt MongoBD-aggregatie gebruiken om het gewenste resultaat te krijgen (neem een ​​kijk ):

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

MongoPlayground

Spring Boot-implementatie

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. Query om alle documenten te vinden met niet-nul milliseconden

  2. Hoe een Mongodb-verzameling te verwijderen met behulp van de verzamelingsnaam in c #

  3. Back-up meteorendatabase met mongodump?

  4. TypeError:Kan methode 'get' van undefined niet aanroepen