首页 \ 问答 \ Meteor:在集合中仅返回嵌套数组中的单个对象(Meteor: Return only single object in nested array within collection)

Meteor:在集合中仅返回嵌套数组中的单个对象(Meteor: Return only single object in nested array within collection)

我试图用Meteor的find().fetch()过滤返回的数据集,只包含一个对象,如果我查询单个子文档但是我收到几个,有些甚至不包含任何子文档,它看起来不是很有用匹配条款。

我有一个简单的混合数据集合,如下所示:

{
    "_id" : ObjectId("570d20de3ae6b49a54ee01e7"),
    "name" : "Entertainment",
    "items" : [
        {
            "_id" : ObjectId("57a38b5f2bd9ac8225caff06"),
            "slug" : "this-is-a-long-slug",
            "title" : "This is a title"
        },
        {
            "_id" : ObjectId("57a38b835ac9e2efc0fa09c6"),
            "slug" : "mc",
            "title" : "Technology"
        }
    ]
}
{
    "_id" : ObjectId("570d20de3ae6b49a54ee01e8"),
    "name" : "Sitewide",
    "items" : [
        {
            "_id" : ObjectId("57a38bc75ac9e2efc0fa09c9"),
            "slug" : "example",
            "name" : "Single Example"
        }
    ]
}

我可以使用MongoDB shell轻松查询嵌套items数组中的特定对象,如下所示:

db.categories.find( { "items.slug": "mc" }, { "items.$": 1 } );

这会返回好的数据,它只包含我想要使用的单个对象:

{
    "_id" : ObjectId("570d20de3ae6b49a54ee01e7"),
    "items" : [
        {
            "_id" : ObjectId("57a38b985ac9e2efc0fa09c8")
            "slug" : "mc",
            "name" : "Single Example"
        }
     ]
}

但是,如果直接尝试Meteor中的类似查询:

/* server/publications.js */
Meteor.publish('categories.all', function () {
    return Categories.find({}, { sort: { position: 1 } });
});
/* imports/ui/page.js */
Template.page.onCreated(function () {
    this.subscribe('categories.all');
});
Template.page.helpers({
    items: function () {
        var item = Categories.find(
            { "items.slug": "mc" },
            { "items.$": 1 } )
        .fetch();
        console.log('item: %o', item);
     }
 });

结果并不理想,因为它返回整个匹配的块,以及嵌套items数组中的每个对象:

{
    "_id" : ObjectId("570d20de3ae6b49a54ee01e7"),
    "name" : "Entertainment",
    "boards" : [
        {
            "_id" : ObjectId("57a38b5f2bd9ac8225caff06")
            "slug" : "this-is-a-long-slug",
            "name" : "This is a title"
        },
        {
            "_id" : ObjectId("57a38b835ac9e2efc0fa09c6")
            "slug" : "mc",
            "name" : "Technology"
        }
    ]
}

然后我当然可以使用for循环进一步过滤返回的游标以获得所需的对象,但是在处理更大的数据集时,这似乎是不可扩展的并且非常低效。

我无法理解为什么Meteor的find返回一个完全不同于MongoDB shell find的数据集,唯一合理的解释是两个函数签名都不同。

我应该将嵌套集合分解为更小的集合并采用更多关系数据库方法(即存储对ObjectID的引用)和查询集合到集合的数据,还是有更强大的方法可用于有效地将大数据集过滤成单个如上所示,只包含匹配对象的对象?


I'm attempting to filter returned data sets with Meteor's find().fetch() to contain just a single object, it doesn't appear very useful if I query for a single subdocument but instead I receive several, some not even containing any of the matched terms.

I have a simple mixed data collection that looks like this:

{
    "_id" : ObjectId("570d20de3ae6b49a54ee01e7"),
    "name" : "Entertainment",
    "items" : [
        {
            "_id" : ObjectId("57a38b5f2bd9ac8225caff06"),
            "slug" : "this-is-a-long-slug",
            "title" : "This is a title"
        },
        {
            "_id" : ObjectId("57a38b835ac9e2efc0fa09c6"),
            "slug" : "mc",
            "title" : "Technology"
        }
    ]
}
{
    "_id" : ObjectId("570d20de3ae6b49a54ee01e8"),
    "name" : "Sitewide",
    "items" : [
        {
            "_id" : ObjectId("57a38bc75ac9e2efc0fa09c9"),
            "slug" : "example",
            "name" : "Single Example"
        }
    ]
}

I can easily query for a specific object in the nested items array with the MongoDB shell as this:

db.categories.find( { "items.slug": "mc" }, { "items.$": 1 } );

This returns good data, it contains just the single object I want to work with:

{
    "_id" : ObjectId("570d20de3ae6b49a54ee01e7"),
    "items" : [
        {
            "_id" : ObjectId("57a38b985ac9e2efc0fa09c8")
            "slug" : "mc",
            "name" : "Single Example"
        }
     ]
}

However, if a similar query within Meteor is directly attempted:

/* server/publications.js */
Meteor.publish('categories.all', function () {
    return Categories.find({}, { sort: { position: 1 } });
});
/* imports/ui/page.js */
Template.page.onCreated(function () {
    this.subscribe('categories.all');
});
Template.page.helpers({
    items: function () {
        var item = Categories.find(
            { "items.slug": "mc" },
            { "items.$": 1 } )
        .fetch();
        console.log('item: %o', item);
     }
 });

The outcome isn't ideal as it returns the entire matched block, as well as every object in the nested items array:

{
    "_id" : ObjectId("570d20de3ae6b49a54ee01e7"),
    "name" : "Entertainment",
    "boards" : [
        {
            "_id" : ObjectId("57a38b5f2bd9ac8225caff06")
            "slug" : "this-is-a-long-slug",
            "name" : "This is a title"
        },
        {
            "_id" : ObjectId("57a38b835ac9e2efc0fa09c6")
            "slug" : "mc",
            "name" : "Technology"
        }
    ]
}

I can then of course filter the returned cursor even further with a for loop to get just the needed object, but this seems unscalable and terribly inefficient while dealing with larger data sets.

I can't grasp why Meteor's find returns a completely different set of data than MongoDB's shell find, the only reasonable explanation is both function signatures are different.

Should I break up my nested collections into smaller collections and take a more relational database approach (i.e. store references to ObjectIDs) and query data from collection-to-collection, or is there a more powerful means available to efficiently filter large data sets into single objects that contain just the matched objects as demonstrated above?


原文:https://stackoverflow.com/questions/38794278
更新时间:2022-04-29 09:04

最满意答案

你可能在这里错过了正确的逻辑,因为它可以像你期望的那样工作。 这是范围的典型问题,因为它们可能远远不够直观。

例如,如果事件A跨越时间t = 2到t = 6,并且您想知道在t = 4和t = 5之间发生了什么事件,除非得到正确的范围,否则您将找不到A.

正确的查询应该是:

SELECT ... WHERE date_s <= :searchd AND date_e >= :searchs

这假设:searchd :searchs到你的范围的结尾,并且:searchs成为开始。 在长形式中,这意味着“查找事件在范围结束之前开始在范围开始之后结束的所有事件”。 我相信这会起作用,就像在人为的例子中那样, 6 >= 52 <= 4这样事件才有资格。


You're probably missing the correct logic here for this to work as you expect. This is a typical problem with ranges as they can be considerably less than intuitive.

For instance, if event A spanned time t=2 through t=6 and you want to know what events were going on between t=4 and t=5, you won't find A unless you get your ranges right.

The correct query should be:

SELECT ... WHERE date_s <= :searchd AND date_e >= :searchs

This presumes :searchd to be the end of your range, and :searchs to be the start. In long form this means "Find all events where the event started before the end of the range and ended after the start of the range." I believe this would work, as in the contrived example, 6 >= 5 and 2 <= 4 so that event would qualify.

相关问答

更多

相关文章

更多

最新问答

更多
  • h2元素推动其他h2和div。(h2 element pushing other h2 and div down. two divs, two headers, and they're wrapped within a parent div)
  • 创建一个功能(Create a function)
  • 我投了份简历,是电脑编程方面的学徒,面试时说要培训三个月,前面
  • PDO语句不显示获取的结果(PDOstatement not displaying fetched results)
  • Qt冻结循环的原因?(Qt freezing cause of the loop?)
  • TableView重复youtube-api结果(TableView Repeating youtube-api result)
  • 如何使用自由职业者帐户登录我的php网站?(How can I login into my php website using freelancer account? [closed])
  • SQL Server 2014版本支持的最大数据库数(Maximum number of databases supported by SQL Server 2014 editions)
  • 我如何获得DynamicJasper 3.1.2(或更高版本)的Maven仓库?(How do I get the maven repository for DynamicJasper 3.1.2 (or higher)?)
  • 以编程方式创建UITableView(Creating a UITableView Programmatically)
  • 如何打破按钮上的生命周期循环(How to break do-while loop on button)
  • C#使用EF访问MVC上的部分类的自定义属性(C# access custom attributes of a partial class on MVC with EF)
  • 如何获得facebook app的publish_stream权限?(How to get publish_stream permissions for facebook app?)
  • 如何防止调用冗余函数的postgres视图(how to prevent postgres views calling redundant functions)
  • Sql Server在欧洲获取当前日期时间(Sql Server get current date time in Europe)
  • 设置kotlin扩展名(Setting a kotlin extension)
  • 如何并排放置两个元件?(How to position two elements side by side?)
  • 如何在vim中启用python3?(How to enable python3 in vim?)
  • 在MySQL和/或多列中使用多个表用于Rails应用程序(Using multiple tables in MySQL and/or multiple columns for a Rails application)
  • 如何隐藏谷歌地图上的登录按钮?(How to hide the Sign in button from Google maps?)
  • Mysql左连接旋转90°表(Mysql Left join rotate 90° table)
  • dedecms如何安装?
  • 在哪儿学计算机最好?
  • 学php哪个的书 最好,本人菜鸟
  • 触摸时不要突出显示表格视图行(Do not highlight table view row when touched)
  • 如何覆盖错误堆栈getter(How to override Error stack getter)
  • 带有ImageMagick和许多图像的GIF动画(GIF animation with ImageMagick and many images)
  • USSD INTERFACE - > java web应用程序通信(USSD INTERFACE -> java web app communication)
  • 电脑高中毕业学习去哪里培训
  • 正则表达式验证SMTP响应(Regex to validate SMTP Responses)