例如,我有以下类型的集合:
[
{ batch: false, type: '' },
{ batch: false, type: '' },
{ batch: true, type: '123' },
{ batch: true, type: '123' },
{ batch: true, type: '123' },
{ batch: true, type: '234' },
{ batch: true, type: '234' },
{ batch: true, type: '234' },
{ batch: true, type: '234' },
{ batch: true, type: '567' },
{ batch: true, type: '567' }
]
所以问题是,如何返回具有{batch: false}
且如果{batch: true}
仅返回具有相同{type}
字段的第一个对象的对象数组,基本上我想获得以下响应:
[
{ batch: false, type: '' },
{ batch: false, type: '' },
{ batch: true, type: '123' },
{ batch: true, type: '234' },
{ batch: true, type: '567' }
]
答案 0 :(得分:2)
运行以下聚合管道,您需要在#ifndef RIDER_H
#define RIDER_H
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
using std::boolalpha;
#include <cstring>
using std::strcpy;
using std::strlen;
#include <fstream>
using std::ostream;
using std::istream;
using std::ofstream;
using std::ifstream;
class Rider
{
public:
Rider( ) = default;
Rider( const char* name, int age, const char* rank, const char* weyr );
void setName( const char* name );
void setRank( const char * rank );
void setWeyr( const char * weyr );
void setAge( int age ); // required when we enter a new Rider
// from the keyboard
const char* getName( ) const { return name; }
const char* getRank( ) const { return rank; }
const char* getWeyr( ) const { return weyr; }
int getAge( ) const { return age; }
friend ostream& operator << ( ostream& os, const Rider& r);
friend istream& operator >> ( istream& is, Rider& r );
friend ofstream& operator << ( ofstream& os, const Rider& r );
friend ifstream& operator >> ( ifstream& is, Rider & r );
private:
char * name = nullptr;
char * rank = nullptr;
char * weyr = nullptr;
int age = 0;
};
#endif
键中具有满足给定条件的条件:
$group
答案 1 :(得分:2)
尝试以下聚合管道
db.getCollection('yourCollection').aggregate([
{
$group: {
_id: {
k1: {
$cond: {
if: "$batch",
then: null,
else: "$_id"
}
},
k2: "$type"
},
batch: { $first: "$batch" },
type: { $first: "$type" }
}
},
{
$project: {
_id: 0,
batch: 1,
type: 1
}
}
])
导致
/* 1 */
{
"batch" : false,
"type" : ""
}
/* 2 */
{
"batch" : false,
"type" : ""
}
/* 3 */
{
"batch" : true,
"type" : "123"
}
/* 4 */
{
"batch" : true,
"type" : "567"
}
/* 5 */
{
"batch" : true,
"type" : "234"
}