如何使用Slice运算符并指定要通过查询查询返回的字段?

时间:2014-02-03 07:36:06

标签: mongodb mongodb-.net-driver

我有这个系列:

Books
[
{
  _id: ObjectId(1),
  Title: Book1,
  Price: 100,
  Tags: ["A", "B", "C"] 
},
{
  _id: ObjectId(2),
  Title: Book2,
  Price: 200,
  Tags: ["C", "D", "E"] 
}
]

I want to return only _id field and the first element from the Tags array

So my result should look like this:

Books
[
{
  _id: ObjectId(1),
  Tags: ["A"] 
},
{
  _id: ObjectId(2),
  Tags: ["C"] 
}
]

标签数组可能很大,我只需要知道第一个位置是什么。

var query = Query.EQ(<My condition here>);
var slice = Fields.Slice("Tags", 1);

return Books.FindAs<MyBookClass>(query).SetFields(slice).ToList(); <- Selects all fields from the document
return Books.FindAs<MyBookClass>(query).SetFields(slice).SetFields("_id", "Tags").ToList(); <- I am get _id but I also everything from the Tags array

This works nicely in command shell. How do I implement this using CSharp driver?
> db.Books.find({ "Price" : 100},{Tags:{$slice:1}, _id:1})

有没有办法指定Slice和我想要阅读的字段?

1 个答案:

答案 0 :(得分:1)

以下适用于我,使用MongoShell的Javascript Native代码。

您可以翻译为C#

db.books.find({},{"Tags":{$slice:1},_id:1})

修改

这个怎么样?

var query = Query.EQ(<My condition here>);
var slice = Fields.Slice("Tags", 1);
var fields = Fields.Include("_id","Tags"); 
return Books.FindAs<MyBookClass>(query).SetFields(fields).SetFields(slice).ToList();