MongoDB $ lookup,其中_id为PHP中的foreignField [英] MongoDB $lookup with _id as a foreignField in PHP

查看:357
本文介绍了MongoDB $ lookup,其中_id为PHP中的foreignField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个,我在桌子上拍头太久了...

I am beating my head on the table for too long with this one...

我有两个MongoDB集合:聊天室"和用户". 聊天室"集合的"user_id"键指向用户"集合中的特定单个用户.

I have two MongoDB collections: "chatroom" and "users". The "chatroom" collection has "user_id" key pointing to a specific single user in "users" collection.

我正在尝试使用$ lookup聚合查询与用户获取聊天室,我目前拥有的就是这个:

I am trying to fetch the chatroom with a user using the $lookup aggregate query, what I currently have is this one:

$this->mongo->chatroom->aggregate(
    array('$lookup' => array(
        'from' => 'users',
        'localField' => 'user_id',
        'foreignField' => '_id',
        'as' => 'user'
    ))
);

但是,这将在集合中返回一个空的用户"字段.奇怪的是,如果我尝试将"_id"替换为设置为_id.$ id的自定义"uid",它将按预期工作:

However, this returns an empty "user" field in the collection. The weird thing is that if I try to replace the "_id" with custom "uid" set to the value of _id.$id, it works as expected:

$this->mongo->chatroom->aggregate(
    array('$lookup' => array(
        'from' => 'users',
        'localField' => 'user_id',
        'foreignField' => 'uid', // uid = _id.$id
        'as' => 'user'
    ))
);

我发现问题是"_id"是ObjectId而"user_id"是字符串.但是我不知道如何很好地解决这个问题...

I figured out the problem is that "_id" is ObjectId while "user_id" is a String. But I don't know how to deal with the problem nicely...

推荐答案

为回答我自己的问题,我通过将"user_id"设置为"MongoId"类的实例而不是纯字符串来解决了该问题.基本上,我将"user_id"存储为:

To answer my own question, I went around the problem by making "user_id" an instance of a "MongoId" class instead of a plain string. Basically, I store "user_id" as:

$mongoObject["user_id"] = new MongoId($this->user_id);

另一种解决方案可能是用值等于"_id.$ id"的"uid"字段修饰对象.

Another solution would probably be decorating the objects with "uid" field with a value equal to "_id.$id".

这篇关于MongoDB $ lookup,其中_id为PHP中的foreignField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆