mongodb - 如何从 Mongodb 中的两个不同集合合并?

标签 mongodb union

我有两个这样的表

表 1:

CREATE TABLE `table_1` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `status` int(11) NOT NULL,
  `date_added` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `table_1` (`id`, `name`, `status`, `date_added`) VALUES
(1, 'CNN', 1, '2018-07-01 00:00:01'),
(2, 'BBC', 1, '2018-07-03 00:00:01'); 

表 2:

CREATE TABLE `table_2` (
  `id` int(11) NOT NULL,
  `title` varchar(100) NOT NULL,
  `status` int(11) NOT NULL,
  `date_added` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `table_2` (`id`, `title`, `status`, `date_added`) VALUES
(1, 'Windows', 1, '2018-07-02 00:00:01'),
(2, 'Linux', 1, '2018-07-04 00:00:01'); 

我的 SQL 查询是这样的

SELECT * FROM
( 
 SELECT id, name, date_added FROM `table_1` 
 UNION 
 SELECT id, title as name, date_added FROM `table_2` 
) 
as new_table order by date_added ASC

我想要的结果如下:

id  name    date_added Ascending 1 

1   CNN     2018-07-01 00:00:01
1   Windows 2018-07-02 00:00:01
2   BBC     2018-07-03 00:00:01
2   Linux   2018-07-04 00:00:01

我无法在 mongodb 中得到这样的结果。

最佳答案

经过更多研究,我能够找到在 mongodb 中使用 union 的解决方案,如下所示:

db.table_1.aggregate([
    { 
    $lookup: {
        from: "table_2",
        pipeline: [],
        as: "table_2"
    }
    },
    {
    $addFields: {
        table_2: {
          $map: {
               input: "$table_2",
               as: "tbl2",
               in: { 
                "_id":"$$tbl2._id", 
                "type": "table_2", 
                "title": "$$tbl2.title", 
                "status": "$$tbl2.status",
                "date_added": "$$tbl2.date_added", 
               }
            }
        }
    }
    },
    {
    $group: {
        _id: null,
        table_1: {
            $push: {
                _id:"$_id",
                type: "table_1", 
                name: "$name",
                status: "$status",
                date_added: "$date_added"
            }
        },
        table_2: {
            $first: "$table_2"
        }
    }
    },
    {
    $project: {
        items: {
            $setUnion: ["$table_1", "$table_2"]
        }
    }
    },
    {
    $unwind: "$items"
    },
    {
    $replaceRoot: {
        newRoot: "$items"
    }
    },
    {
    '$match': { status: true} 
    },
    { '$sort': { date_added: -1 } },
    { '$limit': 10 } 
])

关于mongodb - 如何从 Mongodb 中的两个不同集合合并?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51222861/

相关文章:

c# - 在 linq 编译查询上使用 union

sql - 执行 T-SQL UNION 语句时出错。有什么解释吗?

php - 复杂查询+分页脚本

javascript - Mongoose 将请求对象传递给中间件

javascript - NodeJs 和 nodemailer - 隐藏电子邮件链接和 URL 中的查询参数?

node.js - 缺少架构错误 : Schema hasn't been registered for model during populate

MongoDB Count 和 groupby 子文档

MySQL UNION 查询语法问题

php - 如何在单个 MySQL 语句中使用 GROUP_CONCAT 和 UNION

python - Mongodb _id 字段的排序描述非常慢