查询MongoDB的集合成员资格的更好方法?

2024-09-27 04:28:09 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上,试图找出是否有更好的方法来做这件事,至少可以说有点笨重

我尝试使用三个变量来查询mongoDB数据库,并希望输出一组数字,这些数字表示给定样本中有多少项包含变量的特定集合成员/共现(不是共现概率,而是实际共现概率)。有没有比一个接一个地查询“a和B和C”然后再查询“a和B但不是C”等更简单的方法

查询示例:给定数据库中的100篇报纸文章,关键字A、B和C的所有集合成员身份是什么

输出示例:(输出形式为10,20,20,5,5,10,20,10)

  • A&;B&;C存在:10
  • A&;B(但不是C):20
  • A&;C(但不是B):20
  • A(但不是B或C):5
  • B&;C(但不是A):5
  • B(但不是A或C):10
  • C(但不是A或B):20
  • 无:10

编辑:下面是我试图查询的数据类型示例,主要是词干关键字:

{
"_id" : ObjectId("5af2f38f8ff26c8160a864be"),
"date" : ISODate("2010-03-02T00:00:00.000Z"),
"publication" : "guardian",
"title" : "'After you Conor, age before beauty' – Ian Paisley in his own words",
"keywords" : [ 
    "queen", 
    "church", 
    "associ", 
    "scotland", 
    "intent", 
    "parti",   
    "alli", 
    "northern", 
    "secretari", 
    "age", 
    "gather", 
    "rival",  
    "unit"
],
"article_id" : ObjectId("5a72d72b257e063072ad9605")

}

…以及我目前查询数据库的方式:

counter = article_list.count( { $and: [{keywords: {$in: ["scotland"]}}, {keywords: {$in: ["church"]}},{keywords: {$in: ["queen"]}}] } )
outputArray.append(counter) # A & B & C

counter = article_list.count( { $and: [{keywords: {$in: ["scotland"]}}, {keywords: {$in: ["church"]}},{keywords: {$nin: ["queen"]}}] } )
outputArray.append(counter) # A & B

counter = article_list.count( { $and: [{keywords: {$in: ["scotland"]}}, {keywords: {$nin: ["church"]}},{keywords: {$in: ["queen"]}}] } )
outputArray.append(counter) # A & C

counter = article_list.count( { $and: [{keywords: {$in: ["scotland"]}}, {keywords: {$nin: ["church"]}},{keywords: {$nin: ["queen"]}}] } )
outputArray.append(counter) # ONLY A

counter = article_list.count( { $and: [{keywords: {$nin: ["scotland"]}}, {keywords: {$in: ["church"]}},{keywords: {$in: ["queen"]}}] } )
outputArray.append(counter) # B & C

counter = article_list.count( { $and: [{keywords: {$nin: ["scotland"]}}, {keywords: {$in: ["church"]}},{keywords: {$nin: ["queen"]}}] } )
outputArray.append(counter) # ONLY B

counter = article_list.count( { $and: [{keywords: {$nin: ["scotland"]}}, {keywords: {$nin: ["church"]}},{keywords: {$in: ["queen"]}}] } )
outputArray.append(counter) # ONLY C

print ', '.join(outputArray)

基本上只是想知道是否有更好的方法可以做到这一点,有人可以建议,这不涉及循环通过查询


Tags: and方法incountcounterarticlelistamp

热门问题