【问题标题】:mongodb conversation systemmongodb会话系统
【发布时间】:2012-03-26 04:32:43
【问题描述】:

我正在 mongodb 上实现一个非常简单的对话系统。

这个想法应该是,当我打开一个 convo 时,它应该显示发送和接收的消息。到目前为止一切正常,应该很容易,通过使用像这样的伪代码这样的简单查询:

(from "my_id" AND to "friend_id") OR (from "friend_id" AND to "my_id")

这应该非常简单明了,但是使用 mongodb 查询对我来说看起来很复杂(我来自 mysql)。

我正在尝试这个,但它根本不起作用,并且无法找出错误所在。

$cursor =$collection->find
            (
                array('$or' =>
                    array('$and' => array("from"=>"$profile", "to"=>"$loggeduser")),
                    array('$and' => array("to"=>"$profile", "from"=>"$loggeduser"))
                )
            )->limit(50)->sort(array('date' => -1));

这没有返回任何东西....哪里出错了?

提前致谢。

【问题讨论】:

  • 您使用哪种语言?您是否尝试使用 Mongo shell 直接查询?
  • 啊,忘了说...这是PHP

标签: php mongodb


【解决方案1】:

查看此页面,了解如何进行高级 MongoDB 查询:http://www.mongodb.org/display/DOCS/Advanced+Queries

您可以结合使用$and$in 运算符来获得所需的内容。使用 mongo shell,您的查询将如下所示:

db.yourCollectionName.find({$and: {from: {$in: ["toUser", "loggedOnUser"]}}, {to: {$in: ["toUser", "loggedOnUser"]}}})

我相信这也可能给你等价物:

db.yourCollectionName.find({$and: {$or: [{from: "toUser"}, {to: "toUser"}]}}, {$or: [{from: "loggedOnUser"}, {to: "loggedOnUser"}]}}})

从那里将上述内容转换为您正在使用的语言/DSL,并按日期排序。

在您的代码中,您不需要 ($and => array()) 包装您尝试查找的每个对象。删除它们,看起来像这样:

$cursor = $collection->find(
    array('$or' => 
        array(
            array("from"=>"$profile", "to"=>"$loggeduser"),
            array("to"=>"$profile", "from"=>"$loggeduser")
        )
    )
) ->limit(50)->sort(array('date' => -1));

【讨论】:

  • 是的,我知道,这就是我的代码,我正在将其转换为 PHP mongo 驱动程序代码,但一定有某种我看不到的错误。 ..也许有人会注意到它...感谢您的回答!
  • 再看看我写的。从每个嵌套数组中删除额外的 $and。你不需要 ($and => array()) 包装每个对象......你只需要 $or,我相信。
猜你喜欢
  • 1970-01-01
  • 2012-01-08
  • 1970-01-01
  • 2011-03-07
  • 1970-01-01
  • 2012-09-05
  • 1970-01-01
  • 2018-02-13
  • 2011-08-21
相关资源
最近更新 更多