POJO 到 org.bson.Document,反之亦然

POJO to org.bson.Document and Vice Versa

是否有将 Simple POJO 转换为 org.bson.Document 的简单方法?

我知道有很多方法可以做到这一点:

Document doc = new Document();
doc.append("name", person.getName()):

但是它有更简单、更少错字的方法吗?

关键是,你不需要把手放在 org.bson.Document。

Morphia 会在幕后为您完成这一切。

import com.mongodb.MongoClient;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.DatastoreImpl;
import org.mongodb.morphia.Morphia;
import java.net.UnknownHostException;

.....
    private Datastore createDataStore() throws UnknownHostException {
        MongoClient client = new MongoClient("localhost", 27017);
        // create morphia and map classes
        Morphia morphia = new Morphia();
        morphia.map(FooBar.class);
        return new DatastoreImpl(morphia, client, "testmongo");
    }

......

    //with the Datastore from above you can save any mapped class to mongo
    Datastore datastore;
    final FooBar fb = new FooBar("hello", "world");
    datastore.save(fb);

这里有几个例子:https://mongodb.github.io/morphia/

您可以使用 GsonDocument.parse(String json) 将 POJO 转换为 Document。这适用于 java 驱动程序的版本 3.4.2。

像这样:

package com.jacobcs;

import org.bson.Document;

import com.google.gson.Gson;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class MongoLabs {

    public static void main(String[] args) {
        // create client and connect to db
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        MongoDatabase database = mongoClient.getDatabase("my_db_name");

        // populate pojo
        MyPOJO myPOJO = new MyPOJO();
        myPOJO.setName("MyName");
        myPOJO.setAge("26");

        // convert pojo to json using Gson and parse using Document.parse()
        Gson gson = new Gson();
        MongoCollection<Document> collection = database.getCollection("my_collection_name");
        Document document = Document.parse(gson.toJson(myPOJO));
        collection.insertOne(document);
    }

}

当前 Mongo Java 驱动程序 3.9.1 提供开箱即用的 POJO 支持
http://mongodb.github.io/mongo-java-driver/3.9/driver/getting-started/quick-start-pojo/
假设您有这样一个包含一个嵌套对象的示例集合

db.createCollection("product", {
validator: {
    $jsonSchema: {
        bsonType: "object",
        required: ["name", "description", "thumb"],
        properties: {
            name: {
                bsonType: "string",
                description: "product - name - string"
            },
            description: {
                bsonType: "string",
                description: "product - description - string"
            },
            thumb: {
                bsonType: "object",
                required: ["width", "height", "url"],
                properties: {
                    width: {
                        bsonType: "int",
                        description: "product - thumb - width"
                    },
                    height: {
                        bsonType: "int",
                        description: "product - thumb - height"
                    },
                    url: {
                        bsonType: "string",
                        description: "product - thumb - url"
                    }
                }
            }

        }
    }
}});

1.提供具有适当 CodecRegistry

的 Mongo 数据库 bean
@Bean
public MongoClient mongoClient() {
    ConnectionString connectionString = new ConnectionString("mongodb://username:password@127.0.0.1:27017/dbname");

    ConnectionPoolSettings connectionPoolSettings = ConnectionPoolSettings.builder()
            .minSize(2)
            .maxSize(20)
            .maxWaitQueueSize(100)
            .maxConnectionIdleTime(60, TimeUnit.SECONDS)
            .maxConnectionLifeTime(300, TimeUnit.SECONDS)
            .build();

    SocketSettings socketSettings = SocketSettings.builder()
            .connectTimeout(5, TimeUnit.SECONDS)
            .readTimeout(5, TimeUnit.SECONDS)
            .build();

    MongoClientSettings clientSettings = MongoClientSettings.builder()
            .applyConnectionString(connectionString)
            .applyToConnectionPoolSettings(builder -> builder.applySettings(connectionPoolSettings))
            .applyToSocketSettings(builder -> builder.applySettings(socketSettings))
            .build();

    return MongoClients.create(clientSettings);
}

@Bean 
public MongoDatabase mongoDatabase(MongoClient mongoClient) {
    CodecRegistry defaultCodecRegistry = MongoClientSettings.getDefaultCodecRegistry();
    CodecRegistry fromProvider = CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build());
    CodecRegistry pojoCodecRegistry = CodecRegistries.fromRegistries(defaultCodecRegistry, fromProvider);
    return mongoClient.getDatabase("dbname").withCodecRegistry(pojoCodecRegistry);
}

2。注释您的 POJOS

public class ProductEntity {

    @BsonProperty("name") public final String name;
    @BsonProperty("description") public final String description;
    @BsonProperty("thumb") public final ThumbEntity thumbEntity;

    @BsonCreator
    public ProductEntity(
            @BsonProperty("name") String name,
            @BsonProperty("description") String description,
            @BsonProperty("thumb") ThumbEntity thumbEntity) {
        this.name = name;
        this.description = description;
        this.thumbEntity = thumbEntity;
    }
}

public class ThumbEntity {

    @BsonProperty("width") public final Integer width;
    @BsonProperty("height") public final Integer height;
    @BsonProperty("url") public final String url;

    @BsonCreator
    public ThumbEntity(
            @BsonProperty("width") Integer width,
            @BsonProperty("height") Integer height,
            @BsonProperty("url") String url) {
        this.width = width;
        this.height = height;
        this.url = url;
    }
}

3。查询mongoDB,获取POJOS

MongoCollection<Document> collection = mongoDatabase.getCollection("product");
Document query = new Document();
List<ProductEntity> products = collection.find(query, ProductEntity.class).into(new ArrayList<>());


就是这样!您可以轻松获得您的 POJOS 无需繁琐的手动映射 并且不会失去 运行 本机 mongo 查询

的能力

如果您使用的是 Morphia,则可以使用这段代码将 POJO 转换为文档。

Document document = Document.parse( morphia.toDBObject( Entity ).toString() )

如果您不使用 Morphia,那么您可以通过编写自定义映射并将 POJO 转换为 DBObject 并进一步将 DBObject 转换为字符串然后解析它来实现同样的目的。

我不知道你的 MongoDB 版本。但是现在,不需要将 Document 转换为 POJO,反之亦然。您只需根据要使用的内容、文档或 POJO 创建您的集合,如下所示。

//If you want to use Document
MongoCollection<Document> myCollection = db.getCollection("mongoCollection");
Document doc=new Document();
doc.put("name","ABC");
myCollection.insertOne(doc);


//If you want to use POJO
MongoCollection<Pojo> myCollection = db.getCollection("mongoCollection",Pojo.class);
Pojo obj= new Pojo();
obj.setName("ABC");
myCollection.insertOne(obj);

如果您想使用 POJO,请确保您的 Mongo 数据库配置了正确的代码注册表。

MongoClient mongoClient = new MongoClient();
//This registry is required for your Mongo document to POJO conversion
CodecRegistry codecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(),
        fromProviders(PojoCodecProvider.builder().automatic(true).build()));
MongoDatabase db = mongoClient.getDatabase("mydb").withCodecRegistry(codecRegistry);

不,我认为它对批量插入很有用。我认为批量插入不能与 pojo 一起使用(如果我没记错的话)。 如果有人知道如何使用 bulkInsert

如果你使用 Spring 数据 MongoDB 和 springboot,MongoTemplate 有一个方法可以很好地做到这一点。

Spring Data MongoDB API

这是一个示例。

1.First 在 spring 引导项目中自动装配 mongoTemplate。

@Autowired
MongoTemplate mongoTemplate;

2.Use 服务中的 mongoTemplate

Document doc = new Document();
mongoTemplate.getConverter().write(person, doc);

为此,您需要配置 pom 文件和 yml 以注入 mongotemplate

pom.xml

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
    <version>2.1.10.RELEASE</version>
</dependency>

application.yml

# mongodb config
spring:
  data:
    mongodb:
      uri: mongodb://your-mongodb-url