简体   繁体   English

如何在匹配两个条件的数组中查找集合的所有元素

[英]How to find all elements of a collection in an array that matches two conditions

I've been looking at this documentation , and I tried to implement it here: 我一直在查看此文档 ,并尝试在此处实现它:

customers.find({'name':tenantName,'scripts.author':author},'scripts',function(err,data2){

But this doesn't find what I want it to find. 但这找不到我想要的东西。 and I get back every element of scripts whether scripts.author matches or not. 而且我会返回scripts每个元素,无论scripts.author是否匹配。

What am I doing wrong? 我究竟做错了什么?

My data looks like this 我的数据看起来像这样

{
name: "something"
scripts:[
    {author:"something", data:"data"},
    {author:"something else" data:"data2"},
    {author:"something", data:"data3"}
        ]
}

I'd like to get all the scripts where author matches what I give it 我想获得author匹配我提供的所有scripts

There are a few things wrong here for you to understand about matching in queries like this. 您需要了解一些有关此类查询中匹配的错误信息。 First of all, what your were trying to do was this: 首先,您想做的是:

customer.find(
    { "name":tenantName, "scripts.author": author },
    { "scripts.$" },
    function(err,data2) {

      // work here
})

And that would use the positional $ operator to match the element. 这将使用位置$运算符来匹配元素。 But the problem here is that will only match the first element of the array. 但是这里的问题是只能匹配数组的第一个元素。 This is covered in the documentation. 文档中对此进行了介绍。 The result will be like this: 结果将是这样的:

{ "scripts" : [  {  "author" : "something",  "data" : "data" } ] }

If you need to match muliple elements, then you need to use the aggregate function in order to filter the array contents: 如果需要匹配多个元素,则需要使用聚合函数来过滤数组内容:

customer.aggregate([

    // Match just the documents you want
    { "$match": { "name": tenantName, "scripts.author": author } },

    // Unwind the array
    { "$unwind": "$scripts" },

    // Match to filter just the array elements
    { "$match": { "scripts.author": author } },

    // Push back the array elements
    { "$group": {
        "_id": "$_id",
        "name": { "$first": "$name" },
        "scripts": { "$push": "$scripts" }
    }}

],
function(err,result) {

})

And the results there will be the two elements that match "something" as the author . 结果将有两个author元素。

Why all of this? 为什么所有这些? Well there is the limitation on what can be done with projection that was mentioned. 好了,在提到的投影方面可以做些限制。 But the main reason is that you are not matching elements in the array , but you are matching the document that "contains" the matching elements in the array. 但是主要原因是您匹配数组中的元素,而是要匹配“包含”数组中匹配元素的文档

So if you really want to filter the results, this is how you do it. 因此,如果您真的想过滤结果,这就是您的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM