草庐IT

java - 在 MongoDB 中插入包含集合的对象

coder 2023-10-29 原文

我是 MongoDB/JSON 的新手,所以这可能非常简单,但我找不到满意的答案。

假设我在下面定义了 2 个类(实际上要复杂得多):

public class Instrument {
    public String name;
    public List<Identifier> identifiers;
}

public class Identifier {
    public String type;
    public String value;
}

所以一个 Instrument 可以有多个标识符。 现在我有一个 List<Instrument>我想将其存储在名为“instruments”的 Mongo 集合中。
到目前为止我发现的唯一方法是通过一个一个地插入它们的字段来手动创建每个文档(参见下面完整工作示例中的 getDocFromInstrument 方法)。这是非常麻烦且容易出错的+完全与底层类耦合。

有更好的方法吗?
由于我需要在某个阶段取回信息,因此也欢迎任何关于如何“自动”从数据库中重新创建对象的想法。

有关信息,下面代码的输出是:

{ "_id" : { "$oid" : "4f44db111d8bc98c289b5d82"} , "name" : "inst1" , "identifiers" : [ { "type" : "type1" , "value" : "inst1_type1"} , { "type" : "type2" , "value" : "inst1_type2"}]}
{ "_id" : { "$oid" : "4f44db111d8bc98c289b5d83"} , "name" : "inst2" , "identifiers" : [ { "type" : "type1" , "value" : "inst2_type1"} , { "type" : "type2" , "value" : "inst2_type2"}]}

完整代码:

public class TestMongo {

    private final static String IP = "192.168.3.12";
    private final static String DB_NAME = "test";
    private final static int DEFAULT_PORT = 27017;

    public static void main(String[] args) {
        DB db = null;
        try {
            db = new Mongo(IP, DEFAULT_PORT).getDB(DB_NAME);
            insertSomething(db);
            printContent(db);
            cleanDb(db);
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            if (db != null) {
                db.getMongo().close();
            }
        }
    }

    private static void insertSomething(DB db) {
        Identifier idInst1_1 = new Identifier("type1", "inst1_type1");
        Identifier idInst1_2 = new Identifier("type2", "inst1_type2");
        Identifier idInst2_1 = new Identifier("type1", "inst2_type1");
        Identifier idInst2_2 = new Identifier("type2", "inst2_type2");

        Instrument inst1 = new Instrument("inst1", Arrays.asList(idInst1_1, idInst1_2));
        Instrument inst2 = new Instrument("inst2", Arrays.asList(idInst2_1, idInst2_2));

        BasicDBObject doc1 = getDocFromInstrument(inst1);
        BasicDBObject doc2 = getDocFromInstrument(inst2);

        DBCollection instrumentsCollection = db.getCollection("instruments");
        instrumentsCollection.insert(doc1);
        instrumentsCollection.insert(doc2);
    }

    private static void printContent(DB db) {
        DBCollection instrumentsCollection = db.getCollection("instruments");
        DBCursor cur = instrumentsCollection.find();

        while(cur.hasNext()) {
            System.out.println(cur.next());
        }
    }

    private static void cleanDb(DB db) {
        db.dropDatabase();
    }

    private static BasicDBObject getDocFromInstrument(Instrument instrument) {
    BasicDBObject instrumentDoc = new BasicDBObject();
    instrumentDoc.put("name", instrument.name);
    List<BasicDBObject> identifiers = new ArrayList<>();
    for (Identifier identifier : instrument.identifiers) {
        BasicDBObject identifierDoc = new BasicDBObject();
        identifierDoc.put("type", identifier.type);
        identifierDoc.put("value", identifier.value);
        identifiers.add(identifierDoc);
    }
    instrumentDoc.put("identifiers", identifiers);
        return instrumentDoc;
    }

    static class Instrument {
        public String name;
        public List<Identifier> identifiers;

        public Instrument(String name, List<Identifier> ids) {
            this.name = name;
            this.identifiers = ids;
        }

    }

    static class Identifier {
        public String type = "";
        public String value = "";

        public Identifier(String type, String values) {
            this.type = type;
            this.value = values;
        }

    }
}

最佳答案

看看 Morphia,它是 MongoDB 的 Java ORM:

Morphia - Java ORM to/from MongoDB

我将它用于我的 Java 代码,我的类看起来与您的非常相似。我在其他对象中嵌套对象列表时没有遇到任何问题。 Morphia 使用反射将您的类转换为 JSON,因此它将为您处理大量代码(例如您的 getDocFromInstrument 函数)。希望对您有所帮助。

关于java - 在 MongoDB 中插入包含集合的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9394632/

有关java - 在 MongoDB 中插入包含集合的对象的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  3. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  4. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  5. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

  6. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  7. ruby-on-rails - 未在 Ruby 中初始化的对象 - 2

    我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调

  8. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  9. ruby - 如何在 Rails 4 中使用表单对象之前的验证回调? - 2

    我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser

  10. ruby - 检查字符串是否包含散列中的任何键并返回它包含的键的值 - 2

    我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案

随机推荐