简体   繁体   English

将2个集合合并到一个集合mongoDB中

[英]Combine 2 collections into a single collection mongoDB

I have 2 collections in mongoDB 我在mongoDB中有2个集合

collection 1 收集1

  {
    _id : "123",
    name : "ABC1"
  }

collection 2 收集2

  {
    _id : "456",
    name : "DEF1"
  }

I'm trying to combine write a query that gives me an output like so 我正在尝试结合写一个查询,给我一个像这样的输出

Output 产量

  [
    {
      _id : "123",
      name : "ABC1"
    },
    {
     _id : "456",
     name : "DEF1"
    }
  ]

I've tried lookup but that seems to append 1 collection to the other, I want the collections to be merged like shown in the output. 我尝试过查找,但似乎将1个集合附加到另一个集合,我希望合并集合,如输出中所示。 I have looked at the existing solutions on stack overflow and they all suggest using lookup which does not give me the output that I require. 我已经查看了堆栈溢出的现有解决方案,他们都建议使用lookup ,这不会给我我需要的输出。

进行两个独立的查询并将它们组合在

const output = [query1, query2];

This can be done through javascript code on mongo shell as follow: 这可以通过mongo shell上的javascript代码完成,如下所示:

> var all = []; // initialize a variable with empty values

> db.collection1.find().forEach(function (obj) {all.push(obj);}) // push to all from collection 1

> db.collection2.find().forEach(function (obj) {all.push(obj);}) // push to all from collection 2

> printjson(all) // Print all pushed elements 
[
    {
        "_id" : "123",
        "name" : "ABC1"
    },
    {
        "_id" : "456",
        "name" : "DEF1"
    }
]

Hope this will help you. 希望这会帮助你。 You can perform this on mongo shell. 你可以在mongo shell上执行此操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在mongodb中合并两个集合? - How to combine two collections in mongodb? 将 2 个加入的 collections 插入到新集合 MongoDB 和 javascript - Insert a 2 joined collections to a new collection MongoDB with javascript 使用 MongoDB Shell 在集合中过滤 MongoDB 集合 - Filtering MongoDB collections within collection using MongoDB Shell mongodb / mongoose聚合结合了两个表/集合 - mongodb/mongoose aggregation that combine two table/collection MongoDB-插入两个集合中,一个集合引用另一个集合作为子文档 - MongoDB - insert into two collections, one collection referencing the other as subdocument 如何更新 MongoDB 集合中的每个文档? - How to update every single document in a MongoDB collection? Mongodb - 在一个结果中从多个 collections 中获取所有内容 - Mongodb - GET everything from multiple collections in a single result 维护 MongoDB 服务器上所有数据库和集合的数据库和集合统计信息 - cron 作业 - Maintain database and collection stats of all database and collections on MongoDB server - cron job Winston MongoDB:如何通过管道将日志发送到多个集合,而不是全部发送到一个集合 - Winston MongoDB: How to pipe logs to many collections, instead all goes to one collection 如何使用 Spring 引导、mongodb 和 React.js 在另一个集合中使用 collections 列表? - How can i use list of collections in another collection using Spring boot, mongodb and React.js?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM