我需要帮助为MongoDB中的以下集合编写查询。
以下是ProductGroups的示例层次结构:
>ProductGroup1
- Group1
- product11
- product12
...
- Group2
- product21
>ProductGroup22
- Group21
- product211
- product212
...
- Group22
- product221
...
以下是1个产品组的示例。可以有许多产品组。 样本集:
{"_id":ObjectId("abcd"), "_class":"PGroup",
"name":"test",
"status"=1,
"groups": [
"name":"group1","data": [{"url":"urlofproduct1", "name":"product1"}, {"url":"urlofproduct2", "name":"product2"}, ...],
"name":"group2","data": [{"url":"urlofproduct1", "name":"product1"}, {"url":"urlofproduct2", "name":"product2"}, ...],
...
"name":"group10","data": [{"url":"urlofproduct1", "name":"product1"}, {"url":"urlofproduct2", "name":"product2"}, ...],
]}
答案 0 :(得分:0)
重新构建您的数据,如下所示:
internal class SimpleDispatcherContext : SynchronizationContext
{
private readonly Dispatcher _dispatcher;
private readonly DispatcherPriority _priority;
public SimpleDispatcherContext(Dispatcher dispatcher, DispatcherPriority priority = DispatcherPriority.Normal)
{
_dispatcher = dispatcher;
_priority = priority;
}
public override void Post(SendOrPostCallback d, object state) {
var op = this._dispatcher.BeginInvoke(_priority, d, state);
// here, default sync context just does nothing
if (op.Status == DispatcherOperationStatus.Aborted)
throw new OperationCanceledException("Dispatcher has shut down");
}
public override void Send(SendOrPostCallback d, object state) {
_dispatcher.Invoke(d, _priority, state);
}
}
private async Task LoadData()
{
SynchronizationContext.SetSynchronizationContext(new SimpleDispatcherContext(Dispatcher));
// Fetch data
var data = await FetchData();
// Display data
// ...
}
此外,我希望您尝试查找所有产品组中所有产品的总数。试试这个问题,如果这就是你要找的东西:
/* 1 */
{
"_id" : "abcd",
"_class" : "PGroup",
"name" : "test",
"status" : 1,
"groups" : [
{
"name" : "group1",
"data" : [
{
"url" : "urlofproduct1",
"name" : "product1"
},
{
"url" : "urlofproduct2",
"name" : "product2"
}
]
},
{
"name" : "group2",
"data" : [
{
"url" : "urlofproduct1",
"name" : "product1"
},
{
"url" : "urlofproduct2",
"name" : "product2"
}
]
},
{
"name" : "group10",
"data" : [
{
"url" : "urlofproduct1",
"name" : "product1"
},
{
"url" : "urlofproduct2",
"name" : "product2"
}
]
}
]
}
db.collection.aggregate([
{$match:{status:1}},
{$unwind:"$groups"},
{$unwind:"$groups.data"},
{$group:{_id:null,count:{$sum:1}}}
])
将为您提供所有群组的产品总数。如果您需要查找每个产品组下的总产品数量,则查询会有所不同,只需在count
上$group
,如果这符合您的要求。希望这能回答你的问题。