简体   繁体   English

Spring 引导 java 与 Mongodb

[英]Spring Boot java with Mongodb

package com.javatechie.spring.mongo.api.resource;

import java.util.List;
import java.util.Optional;

import org.bson.Document;
import org.bson.json.JsonReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.QualifierAnnotationAutowireCandidateResolver;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.javatechie.spring.mongo.api.model.Book;
import com.javatechie.spring.mongo.api.repository.BookRepository;

@RestController
public class BookController {

    @Autowired
    private BookRepository repository;

    @Autowired
    private  MongoTemplate mongoTemplate;

    @PostMapping("/addBook")
    public String saveBook(@RequestBody Book book) {
        repository.save(book);
        return "Added book with id : " + book.getId();
    }

   @GetMapping("/findAllBooks")
   public List<Book> getBooks() {
       String jsonCommand = "{ aggregate: 'Book', pipeline: [ { $project: { _id: 0, 'bookName': 1 
    } } ], cursor: { } }";
       Document resultDoc = mongoTemplate.executeCommand(jsonCommand);
       System.out.println(resultDoc);
       return repository.findAll();
   }

I am successfully able to print a specific field on the console using this我可以成功地使用这个在控制台上打印一个特定的字段
String jsonCommand = "{ aggregate: 'Book', pipeline: [ { $project: { _id: 0, 'bookName': 1 } } ], cursor: { } }"; String jsonCommand = "{ 聚合:'Book',管道:[ { $project: { _id: 0, 'bookName': 1 } } ],cursor: { } }";
but I want to print specific data for example in my bookName field there are many books so I want to print only those which are Python currently it is printing all bookName.但我想打印特定数据,例如在我的 bookName 字段中有很多书,所以我只想打印 Python 目前它正在打印所有 bookName。

Kindly help me out here iam stuck请帮助我在这里我被困住了

I suggest you to add $match to your aggregation pipeline.我建议您将$match添加到您的聚合管道中。 Like {$match:{ "bookName":"Python"}}{$match:{ "bookName":"Python"}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM