MongoDB Composite Key

后端 未结 3 1273
梦毁少年i
梦毁少年i 2020-12-02 18:52

I\'m just getting started with MongoDb and I\'ve noticed that I get a lot of duplicate records for entries that I meant to be unique. I would like to know how to use a compo

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 19:27

    I just noticed that the question is marked as "java", so you'd want to do something like:

    final BasicDBObject id = new BasicDBObject("a", aVal)
            .append("b", bVal)
            .append("c", cVal);
    results = coll.find(new BasicDBObjet("_id", id));
    

    I use Morphia too, but have found (that while it works) it generates lots of errors as it tries to marshall the composite key. I use the above when querying to avoid these errors.

    My original code (which also works):

    final ProbId key = new ProbId(srcText, srcLang, destLang);
    final QueryImpl query = ds.createQuery(Probabilities.class)
      .field("id").equal(key);
    Probabilities probs = (Probabilities) query.get();
    

    My ProbId class is annotated as @Entity(noClassnameStored = true) and inside the Probabilities class, the id field is @Id ProbId id;

提交回复
热议问题