本文介绍了如何过滤对象元素的数组猫鼬?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下架构:
User: {
age: Number,
name: String,
comments: {
added: Date,
body: String
}
}
我需要获取所有用户,并添加大于自定义日期的评论.
I need get all users, with comments added greater than a custom date.
示例数据:
[{
"name": "John",
"age: 21,
"comments": [{
"added": 21-01-12,
"body": "blabla1"
}, {
"added": 21-02-12,
"body": "blabla2"
}, {
"added": 21-01-10,
"body": "blabla3"
}]
}, {
"name": "Bruno",
"age: 33,
"comments": [{
"added": 21-01-10,
"body": "ololo1"
}, {
"added": 21-02-12,
"body": "ololo2"
}, {
"added": 21-01-09,
"body": "ololo3"
}]
}]
我需要所有评论大于 01-01-11
且评论小于此日期的所有用户.
I need all users with all comments greater than 01-01-11
without comments less than this date.
预期结果:
{
"name": "John",
"age: 21,
"comments": [{
"added": 21-01-12,
"body": "blabla1"
}, {
"added": 21-02-12,
"body": "blabla2"
}]
}, {
"name": "Bruno",
"age: 33,
"comments": [{
"added": 21-02-12,
"body": "ololo2"
}]
}
我该怎么做?
推荐答案
const findQuery = [
{$unwind: "$comments" },
{$match: {"comments.added": {$gt: lastUpdate} } },
{$group: {_id: "$_id", comments: {$push: "$comments"} } }
];
User.aggregate(findQuery)
这篇关于如何过滤对象元素的数组猫鼬?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!