MongoDB聚合:如何检查数组中是否存在包含多个属性的对象

编程入门 行业动态 更新时间:2024-10-26 09:31:48
本文介绍了MongoDB聚合:如何检查数组中是否存在包含多个属性的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个对象数组,我想检查是否存在匹配多个属性的对象.我已经尝试过使用$in和$and,但是它不能按照我想要的方式工作.

I have an array of objects and I want to check if there is an object that matches multiple properties. I have tried using $in and $and but it does not work the way I want it to.

这是我当前的实现.

我有一个像这样的数组

"choices": [ { "name": "choiceA", "id": 0, "l": "k" }, { "name": "choiceB", "id": 1, "l": "j" }, { "name": "choiceC", "id": 2, "l": "l" } ]

我正在尝试编写聚合代码,以检查是否存在同时包含"id":2和"l":"j"属性的对象.我当前的实现检查是否有一个对象包含第一个属性,然后检查是否有一个对象包含第二个属性.

I am trying to write aggregation code that can check if there is an object that contains both "id":2 and "l":"j" properties. My current implementation checks if there is an object containing the first property then checks if there is an object containing the second one.

我如何获得想要的结果?

How can I get my desired results?

下面,请参阅我的聚合查询.完整代码为此处

Below, see my aggregation query. The full code is here

db.poll.aggregate([ { "$match": { "_id": 100 } }, { $project: { numberOfVotes: { $and: [ { $in: [ 2, "$choices.id" ] }, { $in: [ "j", "$choices.l" ] } ] }, } } ])

上面的查询返回true,但属性id:2和"l":"J"的数组中都没有对象.我知道代码按预期工作.我怎样才能得到想要的结果?

The above query returns true yet there is no object in the array both of the properties id:2 and "l":"J". I know the code works as expected. How can I get my desired results?

推荐答案

您要使用 $ elemMatch

db.collection.find({ choices: { $elemMatch: { id: 2, l: "j" } } })

MongoPlayground

编辑

在聚合$project阶段,我将使用 $ filter

In an aggregation $project stage I would use $filter

db.poll.aggregate([ { "$match": { "_id": 100 } }, { $project: { numberOfVotes: { $gt: [ { $size: { $filter: { input: "$choices", as: "choice", cond: { $and: [ { $eq: [ "$$choice.id", 2 ] }, { $eq: [ "$$choice.l", "j" ] } ] } } } }, 0 ] } } } ])

MongoPlayground

更多推荐

MongoDB聚合:如何检查数组中是否存在包含多个属性的对象

本文发布于:2023-11-22 15:19:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617947.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   是否存在   组中   属性   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!