我应该使用什么而不是加入 MongoDB [英] What should I use instead of Join in MongoDB

查看:54
本文介绍了我应该使用什么而不是加入 MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 MongoDB 数据库中有集合,我想编写查询来加入 PHP 中的集合.

I have collections in MongoDB database, i want to write query to join collections in PHP.

我想为相关用户显示新闻.

I want to show the news for relevant user.

我已经搜索过,但不幸的是我没有找到令人信服的答案.

I have searched but unfortunately I have not found a compelling answer.

数据如下:

users
{
"_id": "4ca30369fd0e910ecc000006",
"login": "user11",
"pass": "example_pass",
"date": "2017-12-15"
}
news
{
"_id": "4ca305c2fd0e910ecc000003",
"name": "news one",
"content": "news one",
"user_id": "4ca30373fd0e910ecc000007",
"date": "2017-12-15"
}

推荐答案

使用 mongoose .populate() 在 mongodb 中实现连接是一种方法.如果你想在 MongoDB 数据库级别实现连接,那么你应该尝试 aggregation 管道和 $lookup

To implement joins in mongodb using mongoose .populate() is the one way. If you want to implement joins at MongoDB database level then you should try aggregation pipeline and $lookup

db.news.aggregate([ 
  $lookup : { 
  from : 'users', 
  localField : 'user_id', 
  foreignField : '_id', 
  as : 'user' 
 } 
])

您可以使用 $match 添加条件并过滤查询结果.

You can use $match to add condition and filter the result of query.

这篇关于我应该使用什么而不是加入 MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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