[英]How to get the element in the array in mongoose/mongodb except the element we passed?
这是“ Conversations
”集合的文档结构。 它在消息数组内部的对象中包含参与者数组。 Messages数组包含多个消息对象,如下所示:
{
"_id": "5540b34347fdd4e917b80aa4",
"messages": [{
"from": "5530af38576214dd3553331c",
"_id": "5540d5dc22f922061f68a41d",
"participants": ["5530af38576214dd3553331c", "553f280040d50ef20f8c9d66"]
}]
}
在这里,我有messages.from
数据,我想从messages.participants
数组中获取元素,除了messages.from
元素。
在上面的示例中, from
5530af38576214dd3553331c
。因此,我必须从messages.participants
数组中获取元素553f280040d50ef20f8c9d66
。
上面有几个文档,对于每个文档,我们都必须这样做。
我如何在Moongoose / mongodb中做到这一点?
Mongo 聚合和$ unwind用于检查您的条件是否符合以下查询:
db.collectionName.aggregate({
"$unwind": "$messages" // first unwind messages array
}, {
"$match": {
"messages.from": "5530af38576214dd3553331c" //match critreia
}
}, {
"$unwind": "$messages.participants" // unwind participants array
}, {
"$match": {
"messages.participants": {
"$ne": "5530af38576214dd3553331c" // check messages.from not equals participants array
}
}
}, {
"$project": {
"_id": 0,
"participants": "$messages.participants"
}
}).pretty()
您可以使用的方法之一是使用lodash库,尤其是您希望使用差值方法。 这将使用SameValueZero
进行相等比较,以创建一个排除提供的数组的所有值的数组。 注: SameValueZero
比较类似于严格相等比较,例如===
,不同之处在于NaN
与NaN
匹配。
因此,您可以尝试以下操作:
Conservations.where("_id": "5540b34347fdd4e917b80aa4")
.select({"messages": { "$elemMatch": {"from": "5530af38576214dd3553331c"}})
.exec(function (err, docs){
var set_difference = _.difference(["5530af38576214dd3553331c"], docs[0].messages.participants);
console.log(set_difference); // => ["553f280040d50ef20f8c9d66"]
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.