我有一个这样的注册数据结构:
event: "Event A",
level: "A",
field: "Main",
buyer: ["thisuser@gmail.com"],
players: [
{
first: "Bob",
last: "Baker",
email: "bobbaker@gmail.com",
myid: 1234567,
signed: false
},
{
first: "John",
last: "Doe",
email: "johndoe@who.com",
myid: 4325678,
signed: true
}
]
我正在尝试查询已注册不同级别事件的玩家。到目前为止,我有:
db.registrations.aggregate(
[
{ $unwind: '$players' },
{
$group: {
_id: { myid: '$players.myid' },
events: {
$push: {
event: '$event',
level: '$level',
field: '$field',
buyer: ['$buyer']
}
}
}
},
{ $match: { events: { $size: 2 }, 'events.level': 'A' } }
])
我认为如果能够将所有events.level与events数组中的第一条记录进行比较,则聚合的最后一行将起作用。我就是不知道我希望数据输出如下:
{
"_id" : { "myid" : 1081245 },
"events" : [
{ "event" : "Women's AA", "level" : "AA", "field" : "PAL", "buyer" : [ "email@osu.edu" ] },
{ "event" : "COED A", "level" : "A", "field" : "Main", "buyer" : [ "ngruber@cdeducation.org" ] } ] }
{ "_id" : { "myid" : 1081202 },
"events" : [
{ "event" : "Women's BB", "level" : "BB", "field" : "PAL", "buyer" : [ "amothermail@gmail.com" ] },
{ "event" : "COED A", "level" : "A", "field" : "Main", "buyer" : [ "emailing@gmail.com" ] } ] }
{ "_id" : { "myid" : 1081196 },
"events" : [
{ "event" : "Men's A", "level" : "A", "field" : "PAL", "buyer" : [ "myemail@outlook.com" ] },
{ "event" : "COED BB", "level" : "BB", "field" : "Main", "buyer" : [ "hisemail@gmail.com" ] } ] }
{ "_id" : { "myid" : 1080246 },
"events" : [
{ "event" : "Men's A", "level" : "A", "field" : "PAL", "buyer" : [ "dude@outlook.com" ] },
{ "event" : "COED BB", "level" : "BB", "field" : "Main", "buyer" : [ "fella@gmail.com" ] } ] }
我尝试将聚合的最后一行更改为:
{ $match: { events: { $size: 2 }, {$not: {'events.level': '$first'} }} }
我该怎么做?
答案 0 :(得分:0)
要检查所有元素是否不相同,可以检查是否有与第一个元素不同的元素。要首先捕获,可以使用$let,然后可以使用$map运算符将所有events
与第一个元素进行比较。这使您可以申请$anyElemenTrue,请尝试:
db.collection.aggregate([
// other pipeline stages
{
$match: {
$expr: {
$let: {
vars: { first: { $arrayElemAt: [ "$events", 0 ] } },
in: {
$anyElementTrue: {
$map: {
input: "$events",
in: {
$ne: [ "$$this.level", "$$first.level" ]
}
}
}
}
}
}
}
}
])