如何在聚合的投影上使用$ elemMatch? [英] How to use $elemMatch on aggregate's projection?

查看:170
本文介绍了如何在聚合的投影上使用$ elemMatch?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的对象

{ "_id" : ObjectId("53fdcb6796cb9b9aa86f05b9"), "list" : [ "a", "b" ], "complist" : [ { "a" : "a", "b" : "b" }, { "a" : "c", "b" : "d" } ] }

这就是我要完成的事情:检查列表"是否包含某个元素,并在读取文档时从"complist"上的对象中仅获取字段"a",而不考虑这些值中的任何一个.我正在构建一个论坛系统,这是将返回论坛详细信息的查询.我需要在知道用户是否在论坛的白名单中的同时阅读论坛的信息.

And this is what I want to accomplish: check if "list" contains a certain element and get only the field "a" from the objects on "complist" while reading the document regardless of any of these values. I'm building a forum system, this is the query that will return the details of a forum. I need to read the forum information while knowing if the user is in the forum's white list.

有了查找,我就可以使用查询

With a find I can use the query

db.itens.find({},{list:{$elemMatch:{$in:["a"]}}})

仅获取与特定值匹配的第一个元素.这样,我可以只检查返回的数组是否不为空,并且知道列表"是否包含我要查找的值.我无法在查询中执行此操作,因为无论文档是否包含我要在列表"值中查找的值,我都想要该文档.我需要文档,并且知道列表"是否具有特定值.

to get only the first element that matches a certain value. This way I can just check if the returned array is not empty and I know if "list" contains the value I'm looking for. I can't do it on the query because I want the document regardless of it containing the value I'm looking for in the "list" value. I need the document AND know if "list" has a certain value.

通过汇总,我可以使用查询

With an aggregate I can use the query

db.itens.aggregate({$project:{"complist.a":1}})

仅读取complist中包含的对象的字段"a".这将获得论坛线程的基本信息,我不希望线程的所有信息,只是两件事.

to read only the field "a" of the objects contained in complist. This is going to get the forum's threads basic information, I don't want all the information of the threads, just a couple of things.

但是当我尝试使用查询时

But when I try to use the query

db.itens.aggregate({$project:{"complist.b":1,list:{$elemMatch:{$in:["a"]}}}})

尝试同时执行这两项操作,这使我出错,提示运算符$ elemMatch无效.

to try and do both, it throws me an error saying the operator $elemMatch is not valid.

我在总计$ elemMatch上做错什么了吗?有没有更好的方法可以做到这一点?

Am I doing something wrong here with the $elemMatch in aggregate? Is there a better way to accomplish this?

推荐答案

好吧,碰巧您可以在查找的投影块上使用"array.field".

Well, it happens you can use "array.field" on a find's projection block.

 db.itens.find({},{"complist.b":1,list:{$elemMatch:{$in:["a"]}}})

我需要什么.

这篇关于如何在聚合的投影上使用$ elemMatch?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆