我有一个MongoDB集合,组。每个组都有一个由成员的唯一ID引用的成员数组。用户可以是多个组的成员。
组数据如下:
{ _id: 1, members: ['1', '3', '5'], status: 'active' }
{ _id: 2, members: ['4', '1', '10', '11'], status: 'inactive' }
{ _id: 3, members: ['1', '2', '9'], status: 'active' }
我正在尝试将活动组的所有成员提取为单个成员ID数组,而不重复。我想使用mongoexport将它们导出到csv文件。
我可以导出相关项目的ID及其成员列表:
mongoexport -h localhost:3001 --db mydbname --collection groups --type=csv --fields _id,members --query '{"status": "active"}' --out mongotestoutput.txt
但是我不知道如何将成员列表合并到单个数组中。我一直在看Aggregation,但我只是迷失在所有不同的选择中,我看不到哪个可以满足我的需求。非常感谢您的帮助。
答案 0 :(得分:0)
先使用Bank: The Enloe State Bank, City: Cooper, State: TX, Closing Date: May 31, 2019, Cert #: 10716, Acquiring Inst: Legend Bank, N. A.
Bank: Washington Federal Bank for Savings, City: Chicago, State: IL, Closing Date: December 15, 2017, Cert #: 30570, Acquiring Inst: Royal Savings Bank
Bank: The Farmers and Merchants State Bank of Argonia, City: Argonia, State: KS, Closing Date: October 13, 2017, Cert #: 17719, Acquiring Inst: Conway Bank
Bank: Fayette County Bank, City: Saint Elmo, State: IL, Closing Date: May 26, 2017, Cert #: 1802, Acquiring Inst: United Fidelity Bank, fsb
Bank: Guaranty Bank, (d/b/a BestBank in Georgia & Michigan) , City: Milwaukee, State: WI, Closing Date: May 5, 2017, Cert #: 30003, Acquiring Inst: First-Citizens Bank & Trust Company
Bank: First NBC Bank, City: New Orleans, State: LA, Closing Date: April 28, 2017, Cert #: 58302, Acquiring Inst: Whitney Bank
Bank: Proficio Bank, City: Cottonwood Heights, State: UT, Closing Date: March 3, 2017, Cert #: 35495, Acquiring Inst: Cache Valley Bank
进行聚合,然后使用$unwind
来创建看起来像您需要的新集合。然后将此新集合导出到CSV文件。
$out
db.test1.insertMany([
{ _id: 1, members: ['1', '3', '5'], status: 'active' },
{ _id: 2, members: ['4', '1', '10', '11'], status: 'inactive' },
{ _id: 3, members: ['9'], status: 'active' }
])
此处和下方用于禁止_id字段
{_id:0}
或者,如果您需要按数组中的状态获取成员,请添加另一个db.test1.aggregate([
{$unwind: "$members"},
{$project:{_id:0}},
{$out:"test2"}
])
db.test2.find({},{_id:0})
{ "members" : "1", "status" : "active" }
{ "members" : "3", "status" : "active" }
{ "members" : "5", "status" : "active" }
{ "members" : "4", "status" : "inactive" }
{ "members" : "1", "status" : "inactive" }
{ "members" : "10", "status" : "inactive" }
{ "members" : "11", "status" : "inactive" }
{ "members" : "9", "status" : "active" }
,$group
阶段:
$addToSet
答案 1 :(得分:0)
This question显示了两种获得所需结果的方法。可接受的答案使用push,reduce和setUnion。较新的答案更简单,使用unwind和addToSet。两者都对我有用,但是我要使用更简单的版本:
db.collection.aggregate([
{ $match: { "status": "active" },
{ $unwind: "$members"},
{ $group:{
_id: 0,
selectedMembers: { $addToSet: '$members' }
}}
])
我正在从此表达式返回的JSON对象中提取所需的数组。