如何在mongodb中插入元数据

时间:2018-08-16 14:55:06

标签: java mongodb mongodb-java

我在MongoDB中非常新。我想用以下格式在MongoDB中创建一个文档:

{
  "_id": ObjectId("5ad60a8b42f59a0066606b8d"),
  "metadata" :{
      "_class" : "eu.ohim.rcd.efi.DocumentEntity",
       "_id" : "RCD201800000001024-0002-0000",
       "provisionalId" : "RCD201800000001024-0002",
       "designApplicationId" : "RCD201800000001024",
        "documentType" : "PROTECTED_VIEW",
         "rcdProtected" : true
   },
   "filename" : "View0000.jpg",
   "aliases" : null,
   "chunkSize" : NumberLong(261120),
   "uploadDate" : ISODate("2018-04-17T14:54:03.782Z"),
   "length" : NumberLong(29179),
   "contentType" : "image/jpeg",
   "md5" : "1402721cc080174ac6ae9c1d51eb68ab"
}

通常,当我们创建文档时,我们会像这样编写Java代码:

   MongoCollection<Document> collection=database.getCollection("rcd");
    Document document=new Document("title","bookstore")
            .append("id", 1)
            .append("description", "Bookstore of cOMPUTER SCIENCE ONLY")
            .append("address", "Sea View Special economic Zone sector-135 Noida")
            .append("phone", "0120213356");
    collection.insertOne(document);
    System.out.println("Document Added sucessfully");

现在,我想附加一个元数据及其架构。那么将以这种结构插入文档的Java代码是什么?

请建议我。

1 个答案:

答案 0 :(得分:0)

metadata是子文档,要插入此文档,请在准备插入文档时附加类型为metadata的名为Document的属性。

例如:

MongoCollection<Document> collection = ...;

// prepare the sub document
Document metadata = new Document("_class", "eu.ohim.rcd.efi.DocumentEntity")
        .append("_id", "RCD201800000001024-0002-0000")
        .append("provisionalId", "RCD201800000001024-0002")
        .append("designApplicationId", "RCD201800000001024")
        .append("documentType", "PROTECTED_VIEW")
        .append("rcdProtected", true);

// prepare the main document
Document document = new Document("filename", "View000.jpg")
        .append("aliases", null)
        .append("chunkSize", 261120L)
        .append("uploadDate", new Date())
        .append("length", 29179L)
        .append("contentType", "image/jpeg")
        .append("md5", "1402721cc080174ac6ae9c1d51eb68ab")
        // don't forget to add the metadata subdocument
        .append("metadata", metadata);

collection.insertOne(document);

Document insertedDocument = collection.find(Filters.eq("filename", "View000.jpg")).first();
System.out.println(insertedDocument.toJson());

上面的代码将插入他的文档:

{
    "_id" : ObjectId("5b76856dc786a00812246f2c"),
    "filename" : "View000.jpg",
    "aliases" : null,
    "chunkSize" : NumberLong(261120),
    "uploadDate" : ISODate("2018-08-17T08:21:01.835Z"),
    "length" : NumberLong(29179),
    "contentType" : "image/jpeg",
    "md5" : "1402721cc080174ac6ae9c1d51eb68ab",
    "metadata" : {
        "_class" : "eu.ohim.rcd.efi.DocumentEntity",
        "_id" : "RCD201800000001024-0002-0000",
        "provisionalId" : "RCD201800000001024-0002",
        "designApplicationId" : "RCD201800000001024",
        "documentType" : "PROTECTED_VIEW",
        "rcdProtected" : true
    }
}