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

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

问题描述

我有这样的架构

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


文档是


And the docs are

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']

上述示例文档中的doc 1

ie doc 1 in the above sample docs

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

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

推荐答案

只要您意识到自己是在ObjectId上进行匹配,而实际上在引用的集合中没有任何内容,则可以使用

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 } }
]})

几乎涵盖了所有解释

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

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