Mongoid 使用数组字段查找数组内没有任何顺序

Mongoid find using an array field without any order inside the array

我有以下记录:

{
    "_id" : ObjectId("54bcc86320db902902000c13"),
    "latest_activity_at" : ISODate("2015-01-19T09:10:40.000Z"),
    "members" : [ 
        "54ad458b20db9004e903ac02", 
        "54ad1d9320db9004e90348b2"
    ],
    "kid_id" : ObjectId("54ad1d9320db9004e90348b2"),
    "updated_at" : ISODate("2015-01-19T09:10:40.000Z"),
    "created_at" : ISODate("2015-01-19T09:03:31.000Z"),
    "token" : "cvq1t-Ml7HLmzQo3mDMdiA"
}

{
    "_id" : ObjectId("54bcca7b20db902902000e28"),
    "latest_activity_at" : ISODate("2015-01-19T09:12:27.000Z"),
    "members" : [ 
        "54ad1d9320db9004e90348b2", 
        "54ad458b20db9004e903ac02"
    ],
    "kid_id" : ObjectId("54ad458b20db9004e903ac02"),
    "updated_at" : ISODate("2015-01-19T09:12:27.000Z"),
    "created_at" : ISODate("2015-01-19T09:12:27.000Z"),
    "token" : "H4Sv2yqXSpdGIsKlD7zsRg"
}

我正在尝试使用以下方法查找记录:

型号

 def message_between_users(member, member2)
        conversation = KidConversation.any_of(members: [member.to_s, member2.to_s] )
        conversation.count
      end

查看

= current_kid.message_between_users(current_kid.id.to_s, k.id.to_s)

但我只得到一条记录,我想找到所有记录,无论数组字段中的顺序如何。

MongoDB 将在数组字段中为您搜索,因此您想说:

where members is current_kid.id.to_s and members is k.id.to_s.

您尝试构建的基础查询是:

db.kid_conversations.find({
  $and: [
    { members: "54ad458b20db9004e903ac02" },
    { members: "54ad1d9320db9004e90348b2" }
  ]
})

您想将 all_of 与两个子句一起使用:

KidConversation.all_of(
  { members: member.to_s },
  { members: member2.to_s }
)

或使用 where:

自己构建 $and
KidConversation.where(:$and => [
  { :members => member.to_s  },
  { :members => member2.to_s }
])

您也可以使用 $all:

The $all operator selects the documents where the value of a field is an array that contains all the specified elements.

感谢 Neil Lunn 提醒。在 MongoDB 术语中,您可以:

db.kid_conversations.find({
  members: {
    $all: [
      "54ad458b20db9004e903ac02",
      "54ad1d9320db9004e90348b2"
    ]
  }
})

在 Mongoid 中转换为其中之一:

KidConversation.where(:members.all => [ member, member2 ].map(&:to_s))
KidConversation.all(:members => [ member, member2 ].map(&:to_s))

这两个 Mongoid 查询在到达 MongoDB 时结果相同,因此请使用对您有意义的版本。