5

Is it possible to query through a DBRef using a single find spec?

user collection

{
    'age': 30
}

post collection

{
    'user': DBRef('user', ...)
}

Is it possible to query for all post who's users are 30 in a single find step? If not, would it be wise to create a javascript function to handle the multi-stage operation or will that cause blocking problems?

Soviut
  • 88,194
  • 49
  • 192
  • 260

3 Answers3

6

it's not possible to do that. i would recommend either:

a) changing your data model so that all of the data is in a single document (might not be possible depending on your case).

b) querying for users who are 30 first, and then doing a second query to get posts where user is $in that list. i would do this client side rather than using server-side JS or anything like that.

mdirolf
  • 7,521
  • 2
  • 23
  • 15
1

I use a Python driver, so forgive my not-so-mongodb syntax:

users = list(db.Users.find({'Age':30}))
posts = list(db.Posts.find({'User':{'$in':users}}))
MFB
  • 19,017
  • 27
  • 72
  • 118
0

Install python bson package. and try as example.

import pymongo
from pymongo import MongoClient
from bson.dbref import DBRef

client = MongoClient('ip', 27017)

client.the_database.authenticate('user', 'password', source='db_name')
db = client['db_name']
user = db['user']
user_id = user.find_one({'email': 'xxxxx@gmail.com'}).get('_id')

client_user_relation = db['client_user_relation']
print(client_user_relation.find_one())
print(user_id)
print(DBRef(collection = "user", id = user_id))
print(client_user_relation.find_one({'user': DBRef(collection = "user", id = user_id)}))
Rinat Mukhamedgaliev
  • 5,401
  • 8
  • 41
  • 59