Mongoose 获取与数组匹配的文档 [英] Mongoose get docs matching the array

查看:12
本文介绍了Mongoose 获取与数组匹配的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的架构

{
    members: [{
         type: Schema.Types.ObjectId,
         ref: 'User'
    }]
    createdAt: {
        type: Date,
        default: Date.now
    }
    ...
}

<小时>

文档是

1-

{
    members:
    ["some id 1", "some id 2"]
},
createdAt: "someTime ago"

2-

{
    members:
    ["some id 1", "some id 2", "some id 3"]
},
createdAt: "someTime ago"

我想找到与元素数组完全匹配的文档

I want to find the docs which match the exact an array of elements

['some id 1', 'some id 2']

即上述示例文档中的文档 1

ie doc 1 in the above sample docs

这怎么可能?
任何帮助将不胜感激.

How this could be possible?
Any help would be appreciated.

推荐答案

只要您确实意识到您匹配的是 ObjectId 而实际上不是引用集合中的任何内容,您就可以使用 $in 运算符:

As long as you do realize that you are matching on the ObjectId and not actually anything in the referenced collection you can use the $in operator:

db.collection.find({ "members": { "$in": [ "some id 1", "some id 2" ] } })

当然,这些是您的实际 ObjectId 值.

Where of course those are your actual ObjectId values.

但如果你真的是指一个包含该数组的文档,那么你只需传入数组:

But if you really mean a document that has exactly that array, then you just pass in the array:

db.collection.find({ "members": [ "some id 1", "some id 2" ] })

如果它必须同时拥有这两个元素但可以拥有其他元素,那么目前您需要使用 $and 表达式:

And if it must have both the elements but could have others then currently you need to use an $and expression:

db.collection.find({ "$and": [ 
    { "members": "some id 1" },
    { "members": "some id 2" } 
]})

但是从 2.6 版开始,您可以正确使用 $all 操作符可以有效地执行相同的操作:

But from release 2.6 an on-wards you can properly use the $all operator to effectively do the same:

db.collection.find({ "members": { "$all": [ "some id 1", "some id 2" ] } })

另一种形式仅匹配这两个元素,但顺序不限.所以有两种方法:

The other form is matching those two elements only, but in any order. So there are two approaches:

db.collection.find({ "$or": [
    { "members": [ "some id 1", "some id 2" ] },
    { "members": [ "some id 2", "some id 1" ] }
]})

这使用逻辑 $or 表示数组必须是精确的,但可以以任何一种方式排列.另一种方法:

This uses a logical $or to say that the array must be exact but can be arranged either way. And the other approach:

db.collection.find({ "$and": [ 
    { "members": "some id 1" },
    { "members": "some id 2" }
    { "members": { "$size": 2 } }
]})

所以这将使用 $size 以确保当数组包含两个匹配的元素时,也只有 两个 元素.这是比使用 $or,尤其是对于较大的数组.

So this would use $size in order to make sure that when the array contained both of the elements that matched that is also only had just two elements. Which is a nicer syntax than using $or, especially for larger arrays.

并且在前面提到的未来版本中,这会变得更加清晰:

And in the future releases as mentioned this gets even cleaner:

db.collection.find({ "$and": [ 
    { "members": { "$all": [ "some id 1", "some id 2" ] } },
    { "members": { "$size": 2 } }
]})

这几乎涵盖了所有解释

这篇关于Mongoose 获取与数组匹配的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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