我有一个聊天集合,在下面给出了
{
"_id" : ObjectId("5a44e6545818041cde24aac9"),
"messages" : [
{
"createdAt" : ISODate("2017-12-23T07:46:29.201Z"),
"message" : "Hii",
"userId" : "000000"
},
{
"createdAt" : ISODate("2017-12-23T12:46:29.201Z"),
"message" : "Bye gtg ttyl",
"userId" : "111111"
},
{
"createdAt" : ISODate("2017-12-24T07:46:29.201Z"),
"message" : "Bye Take Care",
"userId" : "000000"
}
],
"createdAt" : ISODate("2017-10-23T07:46:29.201Z"),
"users" : [
{
"facebookId" : "000000",
"unread" : 0
},
{
"facebookId" : "111111",
"unread" : 0
}
]
}
当我在nodejs
中进行查询后执行此操作chats.aggregate( [ { $unwind : "$messages" },{ $unwind : "$users" } ])
我得到一个类似这样的数组,其中unwind打开我的数组这样的
[
{
"_id": "5a44e6545818041cde24aac9",
"messages": {
"createdAt": "2017-12-23T07:46:29.201Z",
"message": "Hii",
"userId": "000000"
},
"createdAt": "2017-10-23T07:46:29.201Z",
"users": {
"facebookId": "000000",
"unread": 0
}
},
{
"_id": "5a44e6545818041cde24aac9",
"messages": {
"createdAt": "2017-12-23T07:46:29.201Z",
"message": "Hii",
"userId": "000000"
},
"createdAt": "2017-10-23T07:46:29.201Z",
"users": {
"facebookId": "111111",
"unread": 0
},
}, //And so on.
]
但我可以在放松messages.userId !== users.facebookId
直接来自MongoDB的以下对象
[
{
"_id": "5a44e6545818041cde24aac9",
"messages": {
"createdAt": "2017-12-23T07:46:29.201Z",
"message": "Hii",
"userId": "000000"
},
"createdAt": "2017-10-23T07:46:29.201Z",
"users": {
"facebookId": "111111",
"unread": 0
},
},{
"_id": "5a44e6545818041cde24aac9",
"messages": {
"createdAt": "2017-12-23T12:46:29.201Z",
"message": "Bye gtg ttyl",
"userId": "111111"
},
"createdAt": "2017-10-23T07:46:29.201Z",
"users": {
"facebookId": "000000",
"unread": 0
}
}, {
"_id": "5a44e6545818041cde24aac9",
"messages": {
"createdAt": "2017-12-24T07:46:29.201Z",
"message": "Bye Take Care",
"userId": "000000"
},
"createdAt": "2017-10-23T07:46:29.201Z",
"users": {
"facebookId": "111111",
"unread": 0
}
}
]
答案 0 :(得分:1)
您可以包含$match
阶段以仅获取符合此条件的结果:
db.chats.aggregate( [ { $unwind : "$messages" },{ $unwind : "$users" }, {$match:{ 'messages.userId' :{ $ne: 'users.facebookId'} }])
答案 1 :(得分:1)
尝试下面一个
db.coll3.aggregate([{
$unwind: '$users'
}, {
$project: {
messages: 1,
users: 1,
'messages': {
$filter: {
input: '$messages',
as: 'item',
cond: {
$ne: ['$$item.userId', '$users.facebookId']
}
}
}
}
},{ $unwind : "$messages" }
])
这是mongoshell。我注意到你的记录中的零数量并不相等。即使@veeram和@Astro的上述查询给你正确的结果,如果你试过它们,请确保你不要与它们混淆