Skip to content

Instantly share code, notes, and snippets.

@marr

marr/map.js Secret

Created April 14, 2022 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marr/a466f16482be02e098225e2d5e416eea to your computer and use it in GitHub Desktop.
Save marr/a466f16482be02e098225e2d5e416eea to your computer and use it in GitHub Desktop.
use example;
db.dropDatabase();
db.coll1.insertMany([{
created_at: new Date(),
text: 'abc'
}, {
created_at: new Date(),
text: 'bbb'
}]);
db.coll2.insertMany([{
created_at: new Date(),
other: 'foo'
}]);
var pipeline = [
{
$addFields: {
type: 'coll1'
}
},
{
"$unionWith": {
coll: "coll2",
pipeline: [
{
$addFields: {
type: 'coll2'
}
}
]
},
},
{
$group: {
_id: "$type",
type: { $first: '$type' },
data: { $push: "$$ROOT" }
}
},
{
$unset: "_id"
},
{
$unwind: "$data"
},
{
$unset: "data.type"
}
];
db.getCollection("coll1").aggregate(pipeline);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment