使用 MongoDB 从数组中选择唯一字段
我有一个 MongoDB 结构,目前如下所示:
[campaigns] => Array (
[0] => Array (
[campaign_id] => 4e8cba7a0b7aabea08000006
[short_code] => IHEQnP
[users] => Array (
)
)
[1] => Array (
[campaign_id] => 4e8ccf7c0b7aabe508000007
[short_code] => QLU_IY
[users] => Array (
)
)
)
我希望能够做的是搜索短代码,然后返回相关数组。我最初尝试过:
db.users.find({'campaigns.short_code':'IHEQnP'}, {'campaigns.campaign_id':1})
但是,它返回所有数组,而不是仅返回我想要的一个(或字段)。
Mongo 有没有办法获取正确的数组(甚至与数组关联的字段)?或者这是我必须在服务器上做的事情?我正在使用锂框架来检索结果(如果有帮助的话)。
预先感谢:)
丹
I have a MongoDB structure which currently looks like this:
[campaigns] => Array (
[0] => Array (
[campaign_id] => 4e8cba7a0b7aabea08000006
[short_code] => IHEQnP
[users] => Array (
)
)
[1] => Array (
[campaign_id] => 4e8ccf7c0b7aabe508000007
[short_code] => QLU_IY
[users] => Array (
)
)
)
What I would like to be able to do, is search for the short code, and just have the relevant array returned. I initially tried:
db.users.find({'campaigns.short_code':'IHEQnP'}, {'campaigns.campaign_id':1})
However that returns all the arrays, as opposed to just the one (or field) that I want.
Is there a way in Mongo to get the correct array (or even field associated with the array)? Or is that something I would have to do on the server? Am using the lithium framework to retrieve the results (in case it helps).
Thanks in advance :)
Dan
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您使用 campaigns.short_code 之类的条件时,您仍在搜索集合,campaigns 只是文档的属性,您的查找将返回文档。
因此,鉴于这种结构,您无法直接通过查询来实现您想要的结果。
MongoDb 中的数组可以切片,但不能排序:
这将为您提供第一个活动,但由于您无法对其进行排序,因此 IHEQnP 位于顶部,在这种情况下没有任何帮助。
请在此处了解更多信息。
然而,在检索完整文档后,您可以在 Lithium 中非常简单地过滤此内容:
请参阅 Entity::find 的文档 这里
如果活动数量较少,我的解决方案是把它保留在 User 中(只要文档大小不太大,就可以在 PHP 中快速排序和过滤)大的)。
如果预计这一数字会增长,那么请考虑将其移动到自己的模型/集合中,或者重新考虑如何对数据进行建模。
When you use a criteria like campaigns.short_code you are still searching the collection, the campaigns is just a property of a document, your find returns documents.
So given this structure you can not achieve what you want directly by a query.
Arrays in MongoDb can be sliced, but not sorted:
This would give you the first campaign, but as you cant sort it so IHEQnP is at top its of no help in this situation.
Read more here.
You could however filter this quite simple in Lithium after retrieving the full document:
See docs for Entity::find here
My solution would be to keep it in User if the amount of campaigns is low (fast to sort and filter in PHP as long as document size isnt too big).
If this is expected to grow then look at moving it to its own model/collection or re-think how you modelled your data.