首页 > 解决方案 > 将 Java 对象插入 MongoDB,并将日期值作为字符串插入

问题描述

我有以下带有 Java 的 mongoDB 代码,我正在尝试将 TechnologyDetails 插入 mongoDB,并在映射器方法中设置所有值并持久保存到 DB。问题是因为 collection.insertOne() 仅将文档作为参数,在我将 TechnologyDetails pojo 转换为 Document 之后,在插入到 MongoDB 期间,“createdAt”日期数据类型字段作为字符串插入到 DB。任何人都可以帮助解决这个问题,即使在将 pojo 转换为 Document 之后如何保持相同的数据类型。所以我将日期作为日期插入到 mongoDb。谢谢。

final FindIterable<Document> iterable = technologiesCollection
                    .find(and(eq(APPLICATION, techKey.getApplication()), eq(VERSION, techKey.getVersion()),
                            eq(TECHNOLOGY, techKey.getTechnology())));
            final Document document = iterable.first();

            final ObjectMapper mapper = new ObjectMapper();
            final TechnologyDetails technology = mapper.convertValue(document, TechnologyDetails.class);        

            if (technology == null) {
               //mapper method to set the technology fields
                Document tech = mapper(techKey, hosts);         
                try {
                    technologiesCollection.insertOne(tech);
                } catch (Exception e) {
                    LOGGER.error("error", e);
                }

            }

    private Document mapper(final TechnologyKey techKey, final Set<ApplicationHost> hosts) {
            final TechnologyDetails technology = new TechnologyDetails();
            final TransactionDetail txnDetail = new TransactionDetail();
            final UserDetail userDetail = new UserDetail();
            technology.setApplication(techKey.getApplication());
            technology.setVersion(techKey.getVersion());
            technology.setTechnology(techKey.getTechnology());
            if (hosts != null) {
                technology.setApplicationHosts(hosts);
            }
            userDetail.setDsid("123");
            userDetail.setName("APP");
            txnDetail.setCreatedBy(userDetail);
            final Date date = new Date(System.currentTimeMillis());
            txnDetail.setCreatedAt(date);
            technology.setTxnDetails(txnDetail);
            Document document = Document.parse(new JSONObject(technology).toString());
            return document;

        }

标签: javamongodb

解决方案



推荐阅读