运行过滤器时,MongoDB Compass返回所有行

时间:2019-11-25 19:57:04

标签: arrays mongodb mongodb-compass

我试图在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,图层:{$ elemMatch:{id:117368}}})。pretty();

1 个答案:

答案 0 :(得分:1)

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

Retrieve only the queried element in an object array in MongoDB collection