0

我正在尝试在 MongoDB Compass 中运行一个过滤器,它返回所有行而不是我正在寻找的行。我可以在与我的数据库类似的示例数据库上运行过滤器而不会出现任何问题。

https://i.stack.imgur.com/IBivJ.png

这是我用来添加记录并从中选择的代码。

public class NoSQLDataAccess
{
    // Create an instance of data factory
    public NoSQLDataFactory noSQLDataFactory;
    public List<dynamic> DocumentDetails { get; set; }
    private IMongoCollection<dynamic> collection;
    private BsonDocument bsonDocument = new BsonDocument();

    public NoSQLDataAccess() { }
    public void TestNoSQL()
    {
        MongoClient client;
        IMongoDatabase database;
        string connectionString = ConfigurationManager.AppSettings["NoSQLConnectionString"];
        client = new MongoClient(connectionString);
        database = client.GetDatabase("TestDatabase");
        collection = database.GetCollection<dynamic>("TestCollection");
        // Insert
        List<Layer> layers = new List<Layer>();
        layers.Add(new Layer { LayerId = 117368, Description = "BOOTHLAYER" });
        layers.Add(new Layer { LayerId = 117369, Description = "DRAWINGLAYER" });
        layers.Add(new Layer { LayerId = 117370, Description = "LAYER3" });
        List<Element> elements = new List<Element>();
        elements.Add(new Element { ElementId = 9250122, Type = "polyline" });
        elements.Add(new Element { ElementId = 9250123, Type = "polyline" });
        List<dynamic> documentDetails = new List<dynamic>();
        documentDetails.Add(new DrawingDTO { Layers = layers, Elements = elements });
        collection.InsertMany(documentDetails);
        List<FilterDetails> filterDetails = new List<FilterDetails>();
        filterDetails.Add(new FilterDetails { Type = "layers.id", Value = "117368" });
        foreach (FilterDetails detail in filterDetails)
        {
            bsonDocument.Add(new BsonElement(detail.Type, detail.Value));
        }
        List<dynamic> results = collection.Find(bsonDocument.ToBsonDocument()).ToList();
    }
}

我已经能够使用 MongoDB shell 获得所需的结果,但我无法在 C# 中复制结果。

这是 MongoDB shell 中的解决方案:

db.TestCollection.find({"layers.id": 117368}, {_id:0, layers: {$elemMatch: {id: 117368}}}).pretty();

4

1 回答 1

1

我发现了一篇与我的问题相似的帖子,对他们有用。我附加的 C# 代码是在我让它正常工作后如何访问它。我使用 MongoDB Compass 来测试查找/插入/更新/删除。

仅检索 MongoDB 集合中对象数组中的查询元素

于 2019-11-26T15:18:35.157 回答