我正在构建游戏,并且正在使用MongoDB来存储玩家的坐标。我使用的是MongoDB的旧版本,我的代码工作正常,但是我不得不将数据库托管在MongoDB Cloud上,因此我不得不将.NET版本更改为4.X。我下载了新的驱动程序,但由于使用的版本太旧了,一切都变了。
那是我的代码:
public class Coordinate {
public float x { get; set; }
public float y { get; set; }
public float z { get; set; }
}
public class Scores {
[MongoDB.Bson.Serialization.Attributes.BsonElement]
public ObjectId _id { get; set; }
public Coordinate[] Coordinates { get; set; }
public string Player { get; set; }
public float Time { get; set; }
public string Level { get; set; }
}
public static BsonArray arr = new BsonArray();
public static BsonArray arr2 = new BsonArray();
public static IMongoCollection<Scores> highestScoreCollection =
db.GetCollection<Scores>("scores");
我无法插入新文档,我正在使用InsertBatch,并且我更改为insertMany。
arr.Add(new BsonDocument{
{"Coordinates", arr2},
{"Player", "Neuer"},
{"Time", time},
{"Level", scene.name}
});
highestScoreCollection.InsertMany(arr);
我收到此错误:
参数1:无法从“ MongoDB.Bson.BsonDocument”转换为 'System.Collections.Generic.IEnumerable'
我无法迭代我的收藏集:
foreach (var document in highestScoreCollection.Find(new QueryDocument("Level", scene.name)).SetSortOrder(SortBy.Descending("Time"))){
}
我收到此错误:
参数1:无法从“ MongoDB.Bson.BsonArray”转换为 'System.Collections.Generic.IEnumerable'
错误CS0103:名称'SortBy'在当前上下文中不存在
如何修复我的代码?
答案 0 :(得分:0)
以下代码对您的外观如何?如果看起来很吸引人,请查看mongodb驱动程序包装器MongoDB.Entities。它大大简化了mongodb访问。除非您确实需要,否则根本不需要使用Bsondocument
。
using MongoDB.Entities;
using System;
using System.Linq;
namespace StackOverflow
{
public class Program
{
[Name("Scores")]
public class Score : Entity
{
public Coordinate[] Coordinates { get; set; }
public string Player { get; set; }
public float Time { get; set; }
public string Level { get; set; }
}
public class Coordinate
{
public float x { get; set; }
public float y { get; set; }
public float z { get; set; }
}
private static void Main(string[] args)
{
new DB("test");
var coords = new[] {
new Coordinate{ x=1.111f, y=2.222f, z=3.333f},
new Coordinate{ x=1.111f, y=2.222f, z=3.333f},
new Coordinate{ x=1.111f, y=2.222f, z=3.333f}
};
(new[] {
new Score
{
Coordinates = coords,
Player = "player 1",
Time = 0.11f,
Level = "scene a"
}, new Score
{
Coordinates = coords,
Player = "player 2",
Time = 0.22f,
Level = "scene a"
}
}).Save();
var scores = DB.Queryable<Score>()
.Where(s => s.Level == "scene a")
.OrderByDescending(s => s.Time)
.ToArray();
foreach (var score in scores)
{
Console.WriteLine($"player: {score.Player}");
}
Console.ReadKey();
}
}
}
[免责声明:我是图书馆的作者]