【问题标题】:index search returns all subdocuments索引搜索返回所有子文档
【发布时间】:2014-03-25 20:41:25
【问题描述】:

我只想根据文本搜索查询返回名为“列表”的嵌入文档。我可能哪里出错了?创建索引?

这是我的索引: db.Collection.ensureIndex({"Listings.Title": "text", "Listings.Description" : "text"}, {name: "Search"})

这会返回整个对象,只需要列表 db.AspNetUsers.runCommand("text", { search: "lawn" })

这仅返回列表,但包括所有列表。不是基于搜索条件的列表,例如'草地' db.AspNetUsers.runCommand("text", { search: "lawn", project: {Listings:1}})

这是我的对象

{
  "_id" : ,
  "UserName" : "",
  "PasswordHash" : "",
  "SecurityStamp" : "",
  "Roles" : [],
  "Claims" : [],
  "Logins" : [],
  "ProfileData" : {
    "BirthDate" : new Date("3/8/1974 00:00:00"),
    "FirstName" : "",
    "LastName" : "",
    "MiddleName" : "",
    "Address" : "",
    "Address1" : ,
    "City" : "",
    "State" : "",
    "PostalCode" : "",
    "CellPhone" : "",
    "HomePhone" : "",
    "Location" : {
      "type" : "Point",
      "coordinates" : [, ]
    }
  },
  "Email" : "",
  "ConfirmationToken" : "Confirmed",
  "IsConfirmed" : true,
  "Listings" : [{
      "_id" : ObjectId("5331ac28a5eabf2854085df5"),
      "UserId" : ObjectId("5329b43fa5eabf0548490c27"),
      "Title" : "Lawn Chairs",
      "Description" : "lawn chairs",
      "Pictures" : ["5331ac28a5eabf2854085df6", "5331ac28a5eabf2854085df7", "5331ac28a5eabf2854085df8"],
      "Category" : {
        "_id" : ObjectId("53273ce37dd6c71e1859ab77"),
        "Title" : "Leisure"
      }
    }, {
      "_id" : ObjectId("5331ac50a5eabf2854085df9"),
      "UserId" : ObjectId("5329b43fa5eabf0548490c27"),
      "Title" : "Lawn Ornaments",
      "Description" : "lawn ornaments troll frog gnome",
      "Pictures" : ["5331ac50a5eabf2854085dfa", "5331ac50a5eabf2854085dfb", "5331ac51a5eabf2854085dfc"],
      "Category" : {
        "_id" : ObjectId("53273cd57dd6c71e1859ab76"),
        "Title" : "Home"
      }
    }, {
      "_id" : ObjectId("5331ac71a5eabf2854085dfd"),
      "UserId" : ObjectId("5329b43fa5eabf0548490c27"),
      "Title" : "Cell Phone",
      "Description" : "Samsung Galaxy S4",
      "Pictures" : ["5331ac71a5eabf2854085dfe", "5331ac71a5eabf2854085dff", "5331ac72a5eabf2854085e00"],
      "Category" : {
        "_id" : ObjectId("53273cd57dd6c71e1859ab76"),
        "Title" : "Home"
      }
    }]
}

【问题讨论】:

    标签: mongodb full-text-search


    【解决方案1】:

    您可以使用project 参数只获取您想要的字段。要仅获取 Listings 元素,您可以尝试:

    db.AspNetUsers.runCommand("text", {search:"lawn", project:{_id:0, Listings:1}})
    

    编辑:

    文本命令将返回包含搜索词的所有文档。您将获得整个文档。如果您还想过滤文档内部的数组,可以使用$elemMatch 投影运算符,结合$regex。例如:

    db.AspNetUsers.runCommand("text", { 
         search: "lawn", 
         project: {_id:0, Listings:{$elemMatch:{ "Title": /lawn/i }}} 
    })
    

    【讨论】:

    • 感谢您的回复,但我已经尝试过,但它会返回所有列表,而不是仅包含搜索条件的列表。
    • 我已经用一种限制数组内容的方法更新了我的帖子。希望对您有所帮助。
    • 再次感谢您!我会测试一下。
    猜你喜欢
    • 1970-01-01
    • 2014-07-10
    • 2019-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-03
    相关资源
    最近更新 更多