Make an array of multiple arrays in MongoDB?

MongoDBDatabaseBig Data Analytics

To make an array of multiple arrays, use $unwind in MongoDB aggregate. Let us create a collection with documents −

> db.demo289.insertOne({"Section":["A","B","E"],"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4c06fcf49383b52759cbc3")
}
> db.demo289.insertOne({"Section":["C","D","B"],"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4c070af49383b52759cbc4")
}

Display all documents from a collection with the help of find() method −

> db.demo289.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e4c06fcf49383b52759cbc3"),
   "Section" : [ "A", "B", "E" ],
   "Name" : "Chris"
}
{
   "_id" : ObjectId("5e4c070af49383b52759cbc4"),
   "Section" : [ "C", "D", "B" ],
   "Name" : "David"
}

Following is the query to make a single array of multiple arrays in MongoDB −

> db.demo289.aggregate({ $unwind : "$Section" } );

This will produce the following output −

{ "_id" : ObjectId("5e4c06fcf49383b52759cbc3"), "Section" : "A", "Name" : "Chris" }
{ "_id" : ObjectId("5e4c06fcf49383b52759cbc3"), "Section" : "B", "Name" : "Chris" }
{ "_id" : ObjectId("5e4c06fcf49383b52759cbc3"), "Section" : "E", "Name" : "Chris" }
{ "_id" : ObjectId("5e4c070af49383b52759cbc4"), "Section" : "C", "Name" : "David" }
{ "_id" : ObjectId("5e4c070af49383b52759cbc4"), "Section" : "D", "Name" : "David" }
{ "_id" : ObjectId("5e4c070af49383b52759cbc4"), "Section" : "B", "Name" : "David" }
raja
Published on 31-Mar-2020 17:18:24
Advertisements