索引搜索返回所有子文档

时间:2014-03-25 20:41:26

标签: mongodb full-text-search

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

这是我的索引: 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"
      }
    }]
}

1 个答案:

答案 0 :(得分:0)

您可以使用project参数获取所需的字段。要获得Listings元素,您可以尝试:

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

修改

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

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