0

I have two collections

  checkone
    {"_id":1,"name":"alex"},
    {"_id":2,"name":"sandy"}
  checktwo
    {"_id":11,"password":"alex",tenant_id:{$ref:"checkone","$id":1}}
    {"_id":12,"password":"alex",tenant_id:{$ref:"checkone","$id":2}}

I am querying for particular field tenant_id value.

    DB database = mongo.getDB("testcheck");
    DBCollection tenant = database.getCollection("checktwo");
    BasicDBObject query = new BasicDBObject();
    BasicDBObject field = new BasicDBObject();
    field.put("tenant_id.$id", 1);
            DBCursor cursor = tenant.find(query,field);
                while (cursor.hasNext()) {
        System.out.println("cursor value");
        System.out.println(cursor.next().get("tenant_id.$id"));
    }

Output:

cursor value null cursor value null

But when I query System.out.println(cursor.next().get("_id"));

Output: cursor value 11.0 cursor value 12.0

How to query for tenant_id value alone? The output must be cursor value 1, cursor value 2

Jessie
  • 963
  • 5
  • 16
  • 26

1 Answers1

1

You want to use the DBRef class. Here's a rewrite of your original while() loop.

    BasicDBObject query = new BasicDBObject();
    BasicDBObject field = new BasicDBObject();
    DBCursor cursor = tenant.find( query, field );

    while( cursor.hasNext() ) {
        System.out.println( "cursor value" );
        DBRef ref = ( DBRef )cursor.next().get( "tenant_id" );
        System.out.println( ref.getId() );
    }
slee
  • 524
  • 2
  • 6
  • I am getting this exception: Exception in thread "main" java.lang.ClassCastException: com.mongodb.BasicDBObject cannot be cast to com.mongodb.DBRef – Jessie Sep 04 '12 at 13:51
  • Could you examine the contents of the `BasicDBObject` that's returned by `cursor.next()`, which I assume triggers the `ClassCastException`? – slee Sep 04 '12 at 15:21
  • when i do, System.out.println(cursor.next()); the output is { "tenant_id" : { "$id" : 1.0}} – Jessie Sep 04 '12 at 16:09
  • when i do System.out.println(cursor.next().get("tenant_id")); the output is { "$id" : 1.0} @slee – Jessie Sep 04 '12 at 16:13
  • What versions of the driver and backend are you using? – slee Sep 04 '12 at 18:03
  • I'm not sure if I'm reading too much into this, but maybe the `DBRef` isn't resolving because of the `$id` type (eg. `checkone._id = 1` vs. `checkone._id = 1.0`). Could you check if the data type of the `_id` attribute in `checkone`? – slee Sep 04 '12 at 18:36
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/16297/discussion-between-jessie-and-slee) – Jessie Sep 05 '12 at 12:16