mongodb中unwind操作

写入第一条数据

db.mytestcol.insert({user_id:“A_id”,bonus:[{ type:“a” ,amount:1000 },{ type:“b” ,amount:2000 },{ type:“b” ,amount:3000 }]})
WriteResult({ “nInserted” : 1 })

写入第二条数据

db.mytestcol.insert({user_id:“B_id”,bonus:[{ type:“a” ,amount:1000 },{ type:“b” ,amount:2000 },{ type:“b” ,amount:3000 }]})
WriteResult({ “nInserted” : 1 })

查询结果

db.mytestcol.find()
{ “_id” : ObjectId(“5d5371693a62b1702548db41”), “user_id” : “A_id”, “bonus” : [ { “type” : “a”, “amount” : 1000 }, { “type” : “b”, “amount” : 2000 }, { “type” : “b”, “amount” : 3000 } ] }
{ “_id” : ObjectId(“5d5371983a62b1702548db42”), “user_id” : “B_id”, “bonus” : [ { “type” : “a”, “amount” : 1000 }, { “type” : “b”, “amount” : 2000 }, { “type” : “b”, “amount” : 3000 } ] }

使用unwind操作

db.mytestcol.aggregate([{"$unwind":"$bonus"}])

得到结果

db.mytestcol.aggregate([{"$unwind":"$bonus"}])
{ “_id” : ObjectId(“5d5371693a62b1702548db41”), “user_id” : “A_id”, “bonus” : { “type” : “a”, “amount” : 1000 } }
{ “_id” : ObjectId(“5d5371693a62b1702548db41”), “user_id” : “A_id”, “bonus” : { “type” : “b”, “amount” : 2000 } }
{ “_id” : ObjectId(“5d5371693a62b1702548db41”), “user_id” : “A_id”, “bonus” : { “type” : “b”, “amount” : 3000 } }
{ “_id” : ObjectId(“5d5371983a62b1702548db42”), “user_id” : “B_id”, “bonus” : { “type” : “a”, “amount” : 1000 } }
{ “_id” : ObjectId(“5d5371983a62b1702548db42”), “user_id” : “B_id”, “bonus” : { “type” : “b”, “amount” : 2000 } }
{ “_id” : ObjectId(“5d5371983a62b1702548db42”), “user_id” : “B_id”, “bonus” : { “type” : “b”, “amount” : 3000 } }

你可能感兴趣的:(数据库,mongdb)