我有一个我想要聚合的集合,使特定字段不同,但也将其他字段数据添加到该聚合结果中。以下是我的收藏示例
{
"_id": ObjectId("57d6bc99e4b014fc13cf9579"),
"_class": "hbservlet.FinalSubmissions",
"active": true,
"mappedTracks":
[
{ "position": 0, "title": "01. Ain't No Time.mp3", "url": "/published/music/tr157d6bc99e4b014fc13cf9579_.aac" },
{ "position": 1, "title": "02. In Her Mouth.mp3", "url": "/published/music/tr257d6bc99e4b014fc13cf9579_.aac" },
{ "position": 2, "title": "03. Maybach.mp3", "url": "/published/music/tr357d6bc99e4b014fc13cf9579_.aac" }
],
"createdBy": ObjectId("57d6bb99b17ee01a5427af08"),
"userId": ObjectId("57d6bb99b17ee01a5427af08"),
"artistname": "test",
}, {
"_id": ObjectId("14d6bc99ebc942fc13cf9579"),
"_class": "hbservlet.FinalSubmissions",
"active": false,
"mappedTracks": [
{ "position": 0, "title": "partysong.mp3", "url": "/published/music/tr114d6bc99ebc942fc13cf9579_.aac" },
{ "position": 1, "title": "outside", "url": "/published/music/tr214d6bc99ebc942fc13cf9579_.aac" },],
"createdBy": ObjectId("57d6bb99b17ee01a5427af08"),
"userId": ObjectId("57d6bb99b17ee01a5427af08"),
"artistname": "mynameismyname",
}
我使用不同的查询(db.published.distinct(" mappedTracks"))来收集所有的mappedTracks,所以我得到了这个
{ "position": 0, "title": "01. Ain't No Time.mp3", "url": "/published/music/tr157d6bc99e4b014fc13cf9579_.aac" },
{ "position": 1, "title": "02. In Her Mouth.mp3", "url": "/published/music/tr257d6bc99e4b014fc13cf9579_.aac" },
{ "position": 2, "title": "03. Maybach.mp3", "url": "/published/music/tr357d6bc99e4b014fc13cf9579_.aac" },
{ "position": 0, "title": "partysong.mp3", "url": "/published/music/tr114d6bc99ebc942fc13cf9579_.aac" },
{ "position": 1, "title": "outside", "url": "/published/music/tr214d6bc99ebc942fc13cf9579_.aac" }
这是我想要的结果,但我还想将其所属文档的_id,userID,artistname添加到创建的新对象中。
答案 0 :(得分:0)
您可以尝试MongoDB aggregation运算符$unwind和$group。例如:
db.collection.aggregate([
{$unwind:"$mappedTracks"},
{$group:{_id:
{mappedTracks:"$mappedTracks",
id:"$_id",
userId:"$userId",
artistname:"$artistname"
}
}
}
])
请注意,这假设您现在想要所有这四个字段的明确值组合。如果您只想在mappedTracks
上区分,则必须决定如何处理userId
和artistname
的重复值。如果是这种情况,请参阅$first运算符以在重复的情况下使用第一个值。
如果您想在$group
之后重命名某些字段,请参阅聚合运算符$project。
如果此查询是您用例的常用查询,我建议您重新考虑Data Modelling or Document Structure。