dongyuying1507 2012-11-16 19:07
浏览 142
已采纳

在mongodb中使用$ in获取字段

I have a collection and the example datas are like this,

{ L:"images", K:"asdd" } { L:"images", K:"asdd" } { L:"images", K:"asdd" } { L:"images", K:"asdd" } { L:"images", K:"asdd" } { L:"images", K:"asdd" } { L:"images", K:"asdd" } { L:"images", K:"asdd" } { L:"images", K:"asdd" } { L:"images", K:"asdd" } { L:"images", K:"asdd" } { L:"images", K:"asdd" } { L:"images", K:"asdd" }

and other fields are,{L:"cars",K:"asdff"},{L:"table",K:"asgeg"} those fields have at least 20 documents too, what I want as a result is like this

{ L:"images", K:"asdd" } { L:"images", K:"asdd" }

{ L:"cars", K:"asdd" } { L:"cars", K:"asdd" }

{ L:"table", K:"asdd" } { L:"table", K:"asdd" }

I want to get the documents according to their L field, but I want to limit every field's result to two and I have no idea how to manage this, thank you for any reply :)

  • 写回答

1条回答 默认 最新

  • doulong1987 2012-11-19 04:11
    关注

    Given your schema, I don't think there is a way, in a single query, to do what you want. I would recommend a PHP script with a simple foreach loop, or similar, to extract the values you want since you tagged this one as PHP.

    Of course, you can just do it with 3 separate queries, one for each L value, with a limit of 2. I assume that we are really talking about a lot of distinct values and not just the three listed.

    I'm not a PHP guy, so I can't help you out there, but you can use the JavaScript capabilities of the shell similarly like this (I loaded your sample data into a collection called foo and it had an _id field added automatically):

    db.foo.distinct("L").forEach(function(key) {
        db.foo.find({"L" : key}, {_id : 0}).limit(2).forEach(
            function (value) {
                printjson(value);
            }
        )
    })
    

    I used distinct to generate the three values but you could easily just pass it in as an array on the first line like so:

    ['images', 'cars', 'table'].forEach(function(key) {
    

    Either way, the function gave me the following output:

    { "L" : "images", "K" : "asdd" }
    { "L" : "images", "K" : "asdd" }
    { "L" : "cars", "K" : "asdd" }
    { "L" : "cars", "K" : "asdd" }
    { "L" : "table", "K" : "asdd" }
    { "L" : "table", "K" : "asdd" }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效