Composite Key retrival

51 views
Skip to first unread message

Kalyan Srinivas

unread,
Jun 12, 2015, 2:54:46 PM6/12/15
to mor...@googlegroups.com
Hi
I am trying to retrieve a document based on the _id condition,the _id is a composite key 
Sample document looks like this 
{
        "_id" : {
                "business_id" : "b15000077",
                "source" : "web"
        },
        "value" : {
                "Sum" : 4,
                "avg" : 4,
                "count" : 1
        }
}

from mongo console
db.collection_name.find({ _id: {"source":"web","business_id":"b15000077"}}) 
gets me result

From Java
I am using morphia to get this document and my query looks like this 

Query<REntity> q = datastore.createQuery(REntity.class).field("_id").equal("{'source':'web','business_id':'b15000077'}");
REntity r = q.get();

I have tried all variation of the single quote and escaped doubled quote ,

My Entityclass looks like 
@Entity(value = "collection_name",noClassnameStored = true)
public class REntity {
@Id
public String id;
//also tried this as a class IdClass- member web,business_id

public ValueClass value;
...}

Being New to Mongo i just cant figure out where the problem,i believe its the way my query to morphia-mongo is constructed,Please point me in right direction

Justin Lee

unread,
Jun 12, 2015, 3:00:45 PM6/12/15
to mor...@googlegroups.com
Your _id in the database is a (bson) document but your morphia query is a String. These two will never compare.  You can use a complex type for your @Id field and then you can simply pass in a reference to an object of that type.  See the CompoundIdTest for examples:  https://github.com/mongodb/morphia/blob/master/morphia/src/test/java/org/mongodb/morphia/mapping/CompoundIdTest.java

--------------------------------

name     : "Justin Lee", 
  title    : "Software Engineer",
  twitter  : "@evanchooly",
  web      : [ "10gen.com", "antwerkz.com" ],
  location : "New York, NY" }

--
You received this message because you are subscribed to the Google Groups "Morphia" group.
To unsubscribe from this group and stop receiving emails from it, send an email to morphia+u...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Kalyan Srinivas

unread,
Jun 12, 2015, 6:43:06 PM6/12/15
to mor...@googlegroups.com
Thank you so very much, i have this working as expected..

Justin Lee

unread,
Jun 12, 2015, 7:00:26 PM6/12/15
to mor...@googlegroups.com
Any time.  Happy coding.

--------------------------------

name     : "Justin Lee", 
  title    : "Software Engineer",
  twitter  : "@evanchooly",
  web      : [ "10gen.com", "antwerkz.com" ],
  location : "New York, NY" }

--

bbouldin

unread,
Jul 12, 2017, 6:20:16 PM7/12/17
to Morphia
Hi Justin,

As a follow-up, in the CompoundId example, how do you specify the order of fields (e.g. if there was more than just 'name' field)? (The order matters, correct?)

Thanks,
Brad
Reply all
Reply to author
Forward
0 new messages