这个mongo命令(1)返回100
db.collection.aggregate([{$match: {"events._id":{$exists:true}}},{$unwind: "$events"},{$match: {"events._id":{$exists:true}}},{$group: {_id: null, count: {$sum: 1}}}])
这个mongo命令(2)返回80
db.collection.aggregate([{$match: {"events.field":{$exists:true}}},{$unwind: "$events"},{$match: {"events.field":{$exists:true}}},{$group: {_id: null, count: {$sum: 1}}}])
这个mongo命令(2)返回15
db.collection.aggregate([{$match: {"events.field":{$exists:false}}},{$unwind: "$events"},{$match: {"events.field":{$exists:false}}},{$group: {_id: null, count: {$sum: 1}}}])
换句话说,第一个命令返回我的集合中的事件总数,100。第二个命令返回存在'field'的事件,80。第三个命令返回那些'field'不存在的事件,15。不应该(1)+(2)= 100?如何获得5个丢失的事件?
答案 0 :(得分:1)
在#include <stdio.h>
#include "SDL2/SDL.h"
#include "SDL2/SDL_image.h"
int main()
{
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* win = SDL_CreateWindow("test",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
640, 480, 0);
Uint32 render_flags = SDL_RENDERER_ACCELERATED;
SDL_Renderer* rend = SDL_CreateRenderer(win, -1, render_flags);
SDL_Surface* surf = IMG_Load("Workspace/learnSDL/red.png");
if (!surf)
{
printf("%s\n", IMG_GetError());
}
SDL_Texture* tex = SDL_CreateTextureFromSurface(rend, surf);
SDL_Delay(10000);
SDL_DestroyTexture(tex);
SDL_DestroyRenderer(rend);
SDL_DestroyWindow(win);
SDL_Quit();
}
管道中,您需要使用字段$unwind
保留空数组或空数组,否则将丢失缺失或空数组,并且不会将其传递给下一个管道。
在您的收藏中,某些文档没有preserveNullAndEmptyArrays
或events
字段
events.field
样本集
db.collection.aggregate(
[
{ $unwind: { path : "$events", preserveNullAndEmptyArrays : true } },
{ $match: {"events.field":{ $exists:false } } },
{ $group: { _id: null, count: { $sum: 1 } } }
]
)
总计数
> db.collection.find()
{ "_id" : ObjectId("5a5b0a3dc2a7348cbc592b9e"), "name" : "1", "events" : { "field" : "1" } }
{ "_id" : ObjectId("5a5b0a3dc2a7348cbc592b9f"), "name" : "2" }
{ "_id" : ObjectId("5a5b0a3dc2a7348cbc592ba0"), "name" : "3", "events" : { "field" : "2" } }
{ "_id" : ObjectId("5a5b0a3dc2a7348cbc592ba1"), "name" : "1", "events" : { "field" : "1" } }
>
计数> db.collection.count()
4
>
>
events.field exists
计数> db.collection.aggregate(
[
{ $unwind: { path : "$events", preserveNullAndEmptyArrays : true } },
{ $match: { "events.field": { $exists : true } } },
{ $group: { _id: null, count: { $sum: 1 } } }
]
)
{ "_id" : null, "count" : 3 }
>
events.field does not exist