Reputation: 963
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
Upvotes: 0
Views: 2467
Reputation: 534
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() );
}
Upvotes: 1