是否可以使用单个查找规范通过DBRef 进行查询?
用户集合
{
'age': 30
}
帖子收集
{
'user': DBRef('user', ...)
}
是否可以在一个查找步骤中查询所有用户为 30 岁的帖子?如果没有,创建一个javascript函数来处理多阶段操作是否明智,否则会导致阻塞问题?
这是不可能的。我会推荐:
a)更改您的数据模型,以便所有数据都在一个文档中(根据您的情况可能无法实现)。
b)首先查询 30 岁的用户,然后进行第二次查询以获取用户在该列表中 $ 的帖子。我会做这个客户端而不是使用服务器端 JS 或类似的东西。
我使用 Python 驱动程序,所以请原谅我不那么 mongodb 的语法:
users = list(db.Users.find({'Age':30}))
posts = list(db.Posts.find({'User':{'$in':users}}))
安装 python bson包。并尝试作为例子。
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)}))